blob: 341c8592eefabba03174e4450cefcfbe8e14347a [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;
Christopher Tate45281862010-03-05 15:46:30 -080052import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020053import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080054import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080055import android.content.ClipData;
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;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800749 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750
Jeff Sharkeya4620792011-05-20 15:29:23 -0700751 final RemoteCallbackList<IProcessObserver> mProcessObservers
752 = new RemoteCallbackList<IProcessObserver>();
753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 /**
755 * Callback of last caller to {@link #requestPss}.
756 */
757 Runnable mRequestPssCallback;
758
759 /**
760 * Remaining processes for which we are waiting results from the last
761 * call to {@link #requestPss}.
762 */
763 final ArrayList<ProcessRecord> mRequestPssList
764 = new ArrayList<ProcessRecord>();
765
766 /**
767 * Runtime statistics collection thread. This object's lock is used to
768 * protect all related state.
769 */
770 final Thread mProcessStatsThread;
771
772 /**
773 * Used to collect process stats when showing not responding dialog.
774 * Protected by mProcessStatsThread.
775 */
776 final ProcessStats mProcessStats = new ProcessStats(
777 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700778 final AtomicLong mLastCpuTime = new AtomicLong(0);
779 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 long mLastWriteTime = 0;
782
783 /**
784 * Set to true after the system has finished booting.
785 */
786 boolean mBooted = false;
787
Dianne Hackborn7d608422011-08-07 16:24:18 -0700788 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700789 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790
791 WindowManagerService mWindowManager;
792
793 static ActivityManagerService mSelf;
794 static ActivityThread mSystemThread;
795
796 private final class AppDeathRecipient implements IBinder.DeathRecipient {
797 final ProcessRecord mApp;
798 final int mPid;
799 final IApplicationThread mAppThread;
800
801 AppDeathRecipient(ProcessRecord app, int pid,
802 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800803 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 TAG, "New death recipient " + this
805 + " for thread " + thread.asBinder());
806 mApp = app;
807 mPid = pid;
808 mAppThread = thread;
809 }
810
811 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800812 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 TAG, "Death received in " + this
814 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 synchronized(ActivityManagerService.this) {
816 appDiedLocked(mApp, mPid, mAppThread);
817 }
818 }
819 }
820
821 static final int SHOW_ERROR_MSG = 1;
822 static final int SHOW_NOT_RESPONDING_MSG = 2;
823 static final int SHOW_FACTORY_ERROR_MSG = 3;
824 static final int UPDATE_CONFIGURATION_MSG = 4;
825 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
826 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 static final int SERVICE_TIMEOUT_MSG = 12;
828 static final int UPDATE_TIME_ZONE = 13;
829 static final int SHOW_UID_ERROR_MSG = 14;
830 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700832 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700833 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800834 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700835 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
836 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700837 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700838 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700839 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700840 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700841 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700842 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
843 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700844 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800846 static final int FIRST_ACTIVITY_STACK_MSG = 100;
847 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
848 static final int FIRST_COMPAT_MODE_MSG = 300;
849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700851 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700852 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853
854 final Handler mHandler = new Handler() {
855 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800856 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 //}
858
859 public void handleMessage(Message msg) {
860 switch (msg.what) {
861 case SHOW_ERROR_MSG: {
862 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 synchronized (ActivityManagerService.this) {
864 ProcessRecord proc = (ProcessRecord)data.get("app");
865 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 return;
868 }
869 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700870 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800871 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 d.show();
873 proc.crashDialog = d;
874 } else {
875 // The device is asleep, so just pretend that the user
876 // saw a crash dialog and hit "force quit".
877 res.set(0);
878 }
879 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700880
881 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 } break;
883 case SHOW_NOT_RESPONDING_MSG: {
884 synchronized (ActivityManagerService.this) {
885 HashMap data = (HashMap) msg.obj;
886 ProcessRecord proc = (ProcessRecord)data.get("app");
887 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800888 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 return;
890 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800891
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700892 Intent intent = new Intent("android.intent.action.ANR");
893 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800894 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
895 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700896 }
897 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800898 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700899 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700902 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 d.show();
904 proc.anrDialog = d;
905 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700906
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700907 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700909 case SHOW_STRICT_MODE_VIOLATION_MSG: {
910 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
911 synchronized (ActivityManagerService.this) {
912 ProcessRecord proc = (ProcessRecord) data.get("app");
913 if (proc == null) {
914 Slog.e(TAG, "App not found when showing strict mode dialog.");
915 break;
916 }
917 if (proc.crashDialog != null) {
918 Slog.e(TAG, "App already has strict mode dialog: " + proc);
919 return;
920 }
921 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700922 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700923 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
924 d.show();
925 proc.crashDialog = d;
926 } else {
927 // The device is asleep, so just pretend that the user
928 // saw a crash dialog and hit "force quit".
929 res.set(0);
930 }
931 }
932 ensureBootCompleted();
933 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 case SHOW_FACTORY_ERROR_MSG: {
935 Dialog d = new FactoryErrorDialog(
936 mContext, msg.getData().getCharSequence("msg"));
937 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700938 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 } break;
940 case UPDATE_CONFIGURATION_MSG: {
941 final ContentResolver resolver = mContext.getContentResolver();
942 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
943 } break;
944 case GC_BACKGROUND_PROCESSES_MSG: {
945 synchronized (ActivityManagerService.this) {
946 performAppGcsIfAppropriateLocked();
947 }
948 } break;
949 case WAIT_FOR_DEBUGGER_MSG: {
950 synchronized (ActivityManagerService.this) {
951 ProcessRecord app = (ProcessRecord)msg.obj;
952 if (msg.arg1 != 0) {
953 if (!app.waitedForDebugger) {
954 Dialog d = new AppWaitingForDebuggerDialog(
955 ActivityManagerService.this,
956 mContext, app);
957 app.waitDialog = d;
958 app.waitedForDebugger = true;
959 d.show();
960 }
961 } else {
962 if (app.waitDialog != null) {
963 app.waitDialog.dismiss();
964 app.waitDialog = null;
965 }
966 }
967 }
968 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700970 if (mDidDexOpt) {
971 mDidDexOpt = false;
972 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
973 nmsg.obj = msg.obj;
974 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
975 return;
976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 serviceTimeout((ProcessRecord)msg.obj);
978 } break;
979 case UPDATE_TIME_ZONE: {
980 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800981 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
982 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 if (r.thread != null) {
984 try {
985 r.thread.updateTimeZone();
986 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800987 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
989 }
990 }
991 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700992 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700993 case CLEAR_DNS_CACHE: {
994 synchronized (ActivityManagerService.this) {
995 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
996 ProcessRecord r = mLruProcesses.get(i);
997 if (r.thread != null) {
998 try {
999 r.thread.clearDnsCache();
1000 } catch (RemoteException ex) {
1001 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1002 }
1003 }
1004 }
1005 }
1006 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001007 case UPDATE_HTTP_PROXY: {
1008 ProxyProperties proxy = (ProxyProperties)msg.obj;
1009 String host = "";
1010 String port = "";
1011 String exclList = "";
1012 if (proxy != null) {
1013 host = proxy.getHost();
1014 port = Integer.toString(proxy.getPort());
1015 exclList = proxy.getExclusionList();
1016 }
1017 synchronized (ActivityManagerService.this) {
1018 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1019 ProcessRecord r = mLruProcesses.get(i);
1020 if (r.thread != null) {
1021 try {
1022 r.thread.setHttpProxy(host, port, exclList);
1023 } catch (RemoteException ex) {
1024 Slog.w(TAG, "Failed to update http proxy for: " +
1025 r.info.processName);
1026 }
1027 }
1028 }
1029 }
1030 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001032 String title = "System UIDs Inconsistent";
1033 String text = "UIDs on the system are inconsistent, you need to wipe your"
1034 + " data partition or your device will be unstable.";
1035 Log.e(TAG, title + ": " + text);
1036 if (mShowDialogs) {
1037 // XXX This is a temporary dialog, no need to localize.
1038 AlertDialog d = new BaseErrorDialog(mContext);
1039 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1040 d.setCancelable(false);
1041 d.setTitle(title);
1042 d.setMessage(text);
1043 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1044 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1045 mUidAlert = d;
1046 d.show();
1047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 } break;
1049 case IM_FEELING_LUCKY_MSG: {
1050 if (mUidAlert != null) {
1051 mUidAlert.dismiss();
1052 mUidAlert = null;
1053 }
1054 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001056 if (mDidDexOpt) {
1057 mDidDexOpt = false;
1058 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1059 nmsg.obj = msg.obj;
1060 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1061 return;
1062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 ProcessRecord app = (ProcessRecord)msg.obj;
1064 synchronized (ActivityManagerService.this) {
1065 processStartTimedOutLocked(app);
1066 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001067 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001068 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1069 synchronized (ActivityManagerService.this) {
1070 doPendingActivityLaunchesLocked(true);
1071 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001072 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001073 case KILL_APPLICATION_MSG: {
1074 synchronized (ActivityManagerService.this) {
1075 int uid = msg.arg1;
1076 boolean restart = (msg.arg2 == 1);
1077 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001078 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001079 }
1080 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001081 case FINALIZE_PENDING_INTENT_MSG: {
1082 ((PendingIntentRecord)msg.obj).completeFinalize();
1083 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001084 case POST_HEAVY_NOTIFICATION_MSG: {
1085 INotificationManager inm = NotificationManager.getService();
1086 if (inm == null) {
1087 return;
1088 }
1089
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001090 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001091 ProcessRecord process = root.app;
1092 if (process == null) {
1093 return;
1094 }
1095
1096 try {
1097 Context context = mContext.createPackageContext(process.info.packageName, 0);
1098 String text = mContext.getString(R.string.heavy_weight_notification,
1099 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1100 Notification notification = new Notification();
1101 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1102 notification.when = 0;
1103 notification.flags = Notification.FLAG_ONGOING_EVENT;
1104 notification.tickerText = text;
1105 notification.defaults = 0; // please be quiet
1106 notification.sound = null;
1107 notification.vibrate = null;
1108 notification.setLatestEventInfo(context, text,
1109 mContext.getText(R.string.heavy_weight_notification_detail),
1110 PendingIntent.getActivity(mContext, 0, root.intent,
1111 PendingIntent.FLAG_CANCEL_CURRENT));
1112
1113 try {
1114 int[] outId = new int[1];
1115 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1116 notification, outId);
1117 } catch (RuntimeException e) {
1118 Slog.w(ActivityManagerService.TAG,
1119 "Error showing notification for heavy-weight app", e);
1120 } catch (RemoteException e) {
1121 }
1122 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001123 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001124 }
1125 } break;
1126 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1127 INotificationManager inm = NotificationManager.getService();
1128 if (inm == null) {
1129 return;
1130 }
1131 try {
1132 inm.cancelNotification("android",
1133 R.string.heavy_weight_notification);
1134 } catch (RuntimeException e) {
1135 Slog.w(ActivityManagerService.TAG,
1136 "Error canceling notification for service", e);
1137 } catch (RemoteException e) {
1138 }
1139 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001140 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1141 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001142 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001143 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001144 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1145 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001146 }
1147 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001148 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1149 synchronized (ActivityManagerService.this) {
1150 ActivityRecord ar = (ActivityRecord)msg.obj;
1151 if (mCompatModeDialog != null) {
1152 if (mCompatModeDialog.mAppInfo.packageName.equals(
1153 ar.info.applicationInfo.packageName)) {
1154 return;
1155 }
1156 mCompatModeDialog.dismiss();
1157 mCompatModeDialog = null;
1158 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001159 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001160 if (mCompatModePackages.getPackageAskCompatModeLocked(
1161 ar.packageName)) {
1162 int mode = mCompatModePackages.computeCompatModeLocked(
1163 ar.info.applicationInfo);
1164 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1165 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1166 mCompatModeDialog = new CompatModeDialog(
1167 ActivityManagerService.this, mContext,
1168 ar.info.applicationInfo);
1169 mCompatModeDialog.show();
1170 }
1171 }
1172 }
1173 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001174 break;
1175 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001176 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001177 final int pid = msg.arg1;
1178 final int uid = msg.arg2;
1179 final boolean foregroundActivities = (Boolean) msg.obj;
1180 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001181 break;
1182 }
1183 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001184 final int pid = msg.arg1;
1185 final int uid = msg.arg2;
1186 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001187 break;
1188 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001189 case REPORT_MEM_USAGE: {
1190 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1191 if (!isDebuggable) {
1192 return;
1193 }
1194 synchronized (ActivityManagerService.this) {
1195 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001196 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1197 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001198 // avoid spamming.
1199 return;
1200 }
1201 mLastMemUsageReportTime = now;
1202 }
1203 Thread thread = new Thread() {
1204 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001205 StringBuilder dropBuilder = new StringBuilder(1024);
1206 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001207 StringWriter oomSw = new StringWriter();
1208 PrintWriter oomPw = new PrintWriter(oomSw);
1209 StringWriter catSw = new StringWriter();
1210 PrintWriter catPw = new PrintWriter(catSw);
1211 String[] emptyArgs = new String[] { };
1212 StringBuilder tag = new StringBuilder(128);
1213 StringBuilder stack = new StringBuilder(128);
1214 tag.append("Low on memory -- ");
1215 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1216 tag, stack);
1217 dropBuilder.append(stack);
1218 dropBuilder.append('\n');
1219 dropBuilder.append('\n');
1220 String oomString = oomSw.toString();
1221 dropBuilder.append(oomString);
1222 dropBuilder.append('\n');
1223 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001224 try {
1225 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1226 "procrank", });
1227 final InputStreamReader converter = new InputStreamReader(
1228 proc.getInputStream());
1229 BufferedReader in = new BufferedReader(converter);
1230 String line;
1231 while (true) {
1232 line = in.readLine();
1233 if (line == null) {
1234 break;
1235 }
1236 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001237 logBuilder.append(line);
1238 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001239 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001240 dropBuilder.append(line);
1241 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001242 }
1243 converter.close();
1244 } catch (IOException e) {
1245 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001246 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001247 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001248 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001249 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001250 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001251 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001252 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001254 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001255 addErrorToDropBox("lowmem", null, "system_server", null,
1256 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001257 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001258 synchronized (ActivityManagerService.this) {
1259 long now = SystemClock.uptimeMillis();
1260 if (mLastMemUsageReportTime < now) {
1261 mLastMemUsageReportTime = now;
1262 }
1263 }
1264 }
1265 };
1266 thread.start();
1267 break;
1268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
1270 }
1271 };
1272
1273 public static void setSystemProcess() {
1274 try {
1275 ActivityManagerService m = mSelf;
1276
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001277 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001279 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001280 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 if (MONITOR_CPU_USAGE) {
1282 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 ServiceManager.addService("permission", new PermissionController(m));
1285
1286 ApplicationInfo info =
1287 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001288 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001289 mSystemThread.installSystemApplicationInfo(info);
1290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 synchronized (mSelf) {
1292 ProcessRecord app = mSelf.newProcessRecordLocked(
1293 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001294 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001296 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001297 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001298 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 synchronized (mSelf.mPidsSelfLocked) {
1300 mSelf.mPidsSelfLocked.put(app.pid, app);
1301 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001302 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304 } catch (PackageManager.NameNotFoundException e) {
1305 throw new RuntimeException(
1306 "Unable to find android system package", e);
1307 }
1308 }
1309
1310 public void setWindowManager(WindowManagerService wm) {
1311 mWindowManager = wm;
1312 }
1313
1314 public static final Context main(int factoryTest) {
1315 AThread thr = new AThread();
1316 thr.start();
1317
1318 synchronized (thr) {
1319 while (thr.mService == null) {
1320 try {
1321 thr.wait();
1322 } catch (InterruptedException e) {
1323 }
1324 }
1325 }
1326
1327 ActivityManagerService m = thr.mService;
1328 mSelf = m;
1329 ActivityThread at = ActivityThread.systemMain();
1330 mSystemThread = at;
1331 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001332 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 m.mContext = context;
1334 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001335 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336
1337 m.mBatteryStatsService.publish(context);
1338 m.mUsageStatsService.publish(context);
1339
1340 synchronized (thr) {
1341 thr.mReady = true;
1342 thr.notifyAll();
1343 }
1344
1345 m.startRunning(null, null, null, null);
1346
1347 return context;
1348 }
1349
1350 public static ActivityManagerService self() {
1351 return mSelf;
1352 }
1353
1354 static class AThread extends Thread {
1355 ActivityManagerService mService;
1356 boolean mReady = false;
1357
1358 public AThread() {
1359 super("ActivityManager");
1360 }
1361
1362 public void run() {
1363 Looper.prepare();
1364
1365 android.os.Process.setThreadPriority(
1366 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001367 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368
1369 ActivityManagerService m = new ActivityManagerService();
1370
1371 synchronized (this) {
1372 mService = m;
1373 notifyAll();
1374 }
1375
1376 synchronized (this) {
1377 while (!mReady) {
1378 try {
1379 wait();
1380 } catch (InterruptedException e) {
1381 }
1382 }
1383 }
1384
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001385 // For debug builds, log event loop stalls to dropbox for analysis.
1386 if (StrictMode.conditionallyEnableDebugLogging()) {
1387 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1388 }
1389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 Looper.loop();
1391 }
1392 }
1393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 static class MemBinder extends Binder {
1395 ActivityManagerService mActivityManagerService;
1396 MemBinder(ActivityManagerService activityManagerService) {
1397 mActivityManagerService = activityManagerService;
1398 }
1399
1400 @Override
1401 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001402 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1403 != PackageManager.PERMISSION_GRANTED) {
1404 pw.println("Permission Denial: can't dump meminfo from from pid="
1405 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1406 + " without permission " + android.Manifest.permission.DUMP);
1407 return;
1408 }
1409
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001410 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001411 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 }
1413 }
1414
Chet Haase9c1e23b2011-03-24 10:51:31 -07001415 static class GraphicsBinder extends Binder {
1416 ActivityManagerService mActivityManagerService;
1417 GraphicsBinder(ActivityManagerService activityManagerService) {
1418 mActivityManagerService = activityManagerService;
1419 }
1420
1421 @Override
1422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001423 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1424 != PackageManager.PERMISSION_GRANTED) {
1425 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1427 + " without permission " + android.Manifest.permission.DUMP);
1428 return;
1429 }
1430
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001431 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001432 }
1433 }
1434
Jeff Brown6754ba22011-12-14 20:20:01 -08001435 static class DbBinder extends Binder {
1436 ActivityManagerService mActivityManagerService;
1437 DbBinder(ActivityManagerService activityManagerService) {
1438 mActivityManagerService = activityManagerService;
1439 }
1440
1441 @Override
1442 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1443 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1444 != PackageManager.PERMISSION_GRANTED) {
1445 pw.println("Permission Denial: can't dump dbinfo from from pid="
1446 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1447 + " without permission " + android.Manifest.permission.DUMP);
1448 return;
1449 }
1450
1451 mActivityManagerService.dumpDbInfo(fd, pw, args);
1452 }
1453 }
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 static class CpuBinder extends Binder {
1456 ActivityManagerService mActivityManagerService;
1457 CpuBinder(ActivityManagerService activityManagerService) {
1458 mActivityManagerService = activityManagerService;
1459 }
1460
1461 @Override
1462 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001463 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1464 != PackageManager.PERMISSION_GRANTED) {
1465 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1466 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1467 + " without permission " + android.Manifest.permission.DUMP);
1468 return;
1469 }
1470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001472 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1473 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1474 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
1476 }
1477 }
1478
1479 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001480 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001481
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001482 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1483 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1484 mBroadcastQueues[0] = mFgBroadcastQueue;
1485 mBroadcastQueues[1] = mBgBroadcastQueue;
1486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 File dataDir = Environment.getDataDirectory();
1488 File systemDir = new File(dataDir, "system");
1489 systemDir.mkdirs();
1490 mBatteryStatsService = new BatteryStatsService(new File(
1491 systemDir, "batterystats.bin").toString());
1492 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001493 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001494 mOnBattery = DEBUG_POWER ? true
1495 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001496 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001498 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001499 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001500 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501
Jack Palevichb90d28c2009-07-22 15:35:24 -07001502 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1503 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1504
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001505 mConfiguration.setToDefaults();
1506 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001507 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 mProcessStats.init();
1509
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001510 mCompatModePackages = new CompatModePackages(this, systemDir);
1511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 // Add ourself to the Watchdog monitors.
1513 Watchdog.getInstance().addMonitor(this);
1514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 mProcessStatsThread = new Thread("ProcessStats") {
1516 public void run() {
1517 while (true) {
1518 try {
1519 try {
1520 synchronized(this) {
1521 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001522 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001524 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 // + ", write delay=" + nextWriteDelay);
1526 if (nextWriteDelay < nextCpuDelay) {
1527 nextCpuDelay = nextWriteDelay;
1528 }
1529 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001530 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 this.wait(nextCpuDelay);
1532 }
1533 }
1534 } catch (InterruptedException e) {
1535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 updateCpuStatsNow();
1537 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001538 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 }
1541 }
1542 };
1543 mProcessStatsThread.start();
1544 }
1545
1546 @Override
1547 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1548 throws RemoteException {
1549 try {
1550 return super.onTransact(code, data, reply, flags);
1551 } catch (RuntimeException e) {
1552 // The activity manager only throws security exceptions, so let's
1553 // log all others.
1554 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557 throw e;
1558 }
1559 }
1560
1561 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001562 final long now = SystemClock.uptimeMillis();
1563 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1564 return;
1565 }
1566 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1567 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 mProcessStatsThread.notify();
1569 }
1570 }
1571 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 void updateCpuStatsNow() {
1574 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001575 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 final long now = SystemClock.uptimeMillis();
1577 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001580 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1581 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 haveNewCpuStats = true;
1583 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001584 //Slog.i(TAG, mProcessStats.printCurrentState());
1585 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 // + mProcessStats.getTotalCpuPercent() + "%");
1587
Joe Onorato8a9b2202010-02-26 18:56:32 -08001588 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 if ("true".equals(SystemProperties.get("events.cpu"))) {
1590 int user = mProcessStats.getLastUserTime();
1591 int system = mProcessStats.getLastSystemTime();
1592 int iowait = mProcessStats.getLastIoWaitTime();
1593 int irq = mProcessStats.getLastIrqTime();
1594 int softIrq = mProcessStats.getLastSoftIrqTime();
1595 int idle = mProcessStats.getLastIdleTime();
1596
1597 int total = user + system + iowait + irq + softIrq + idle;
1598 if (total == 0) total = 1;
1599
Doug Zongker2bec3d42009-12-04 12:52:44 -08001600 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 ((user+system+iowait+irq+softIrq) * 100) / total,
1602 (user * 100) / total,
1603 (system * 100) / total,
1604 (iowait * 100) / total,
1605 (irq * 100) / total,
1606 (softIrq * 100) / total);
1607 }
1608 }
1609
Amith Yamasanie43530a2009-08-21 13:11:37 -07001610 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001611 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001612 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 synchronized(mPidsSelfLocked) {
1614 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001615 if (mOnBattery) {
1616 int perc = bstats.startAddingCpuLocked();
1617 int totalUTime = 0;
1618 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001619 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001621 ProcessStats.Stats st = mProcessStats.getStats(i);
1622 if (!st.working) {
1623 continue;
1624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001626 int otherUTime = (st.rel_utime*perc)/100;
1627 int otherSTime = (st.rel_stime*perc)/100;
1628 totalUTime += otherUTime;
1629 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 if (pr != null) {
1631 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001632 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1633 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001634 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001635 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001636 } else {
1637 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001638 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001639 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001640 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1641 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001642 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001646 bstats.finishAddingCpuLocked(perc, totalUTime,
1647 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 }
1650 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1653 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001654 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
1656 }
1657 }
1658 }
1659
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001660 @Override
1661 public void batteryNeedsCpuUpdate() {
1662 updateCpuStatsNow();
1663 }
1664
1665 @Override
1666 public void batteryPowerChanged(boolean onBattery) {
1667 // When plugging in, update the CPU stats first before changing
1668 // the plug state.
1669 updateCpuStatsNow();
1670 synchronized (this) {
1671 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001672 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001673 }
1674 }
1675 }
1676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 /**
1678 * Initialize the application bind args. These are passed to each
1679 * process when the bindApplication() IPC is sent to the process. They're
1680 * lazily setup to make sure the services are running when they're asked for.
1681 */
1682 private HashMap<String, IBinder> getCommonServicesLocked() {
1683 if (mAppBindArgs == null) {
1684 mAppBindArgs = new HashMap<String, IBinder>();
1685
1686 // Setup the application init args
1687 mAppBindArgs.put("package", ServiceManager.getService("package"));
1688 mAppBindArgs.put("window", ServiceManager.getService("window"));
1689 mAppBindArgs.put(Context.ALARM_SERVICE,
1690 ServiceManager.getService(Context.ALARM_SERVICE));
1691 }
1692 return mAppBindArgs;
1693 }
1694
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001695 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (mFocusedActivity != r) {
1697 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001698 if (r != null) {
1699 mWindowManager.setFocusedApp(r.appToken, true);
1700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
1703
Dianne Hackborn906497c2010-05-10 15:57:38 -07001704 private final void updateLruProcessInternalLocked(ProcessRecord app,
1705 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001707 int lrui = mLruProcesses.indexOf(app);
1708 if (lrui >= 0) mLruProcesses.remove(lrui);
1709
1710 int i = mLruProcesses.size()-1;
1711 int skipTop = 0;
1712
Dianne Hackborn906497c2010-05-10 15:57:38 -07001713 app.lruSeq = mLruSeq;
1714
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001715 // compute the new weight for this process.
1716 if (updateActivityTime) {
1717 app.lastActivityTime = SystemClock.uptimeMillis();
1718 }
1719 if (app.activities.size() > 0) {
1720 // If this process has activities, we more strongly want to keep
1721 // it around.
1722 app.lruWeight = app.lastActivityTime;
1723 } else if (app.pubProviders.size() > 0) {
1724 // If this process contains content providers, we want to keep
1725 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001726 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001727 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001728 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001729 } else {
1730 // If this process doesn't have activities, we less strongly
1731 // want to keep it around, and generally want to avoid getting
1732 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001733 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001734 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001735 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001737
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001738 while (i >= 0) {
1739 ProcessRecord p = mLruProcesses.get(i);
1740 // If this app shouldn't be in front of the first N background
1741 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001742 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001743 skipTop--;
1744 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001745 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001746 mLruProcesses.add(i+1, app);
1747 break;
1748 }
1749 i--;
1750 }
1751 if (i < 0) {
1752 mLruProcesses.add(0, app);
1753 }
1754
Dianne Hackborn906497c2010-05-10 15:57:38 -07001755 // If the app is currently using a content provider or service,
1756 // bump those processes as well.
1757 if (app.connections.size() > 0) {
1758 for (ConnectionRecord cr : app.connections) {
1759 if (cr.binding != null && cr.binding.service != null
1760 && cr.binding.service.app != null
1761 && cr.binding.service.app.lruSeq != mLruSeq) {
1762 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1763 updateActivityTime, i+1);
1764 }
1765 }
1766 }
1767 if (app.conProviders.size() > 0) {
1768 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001769 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1770 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001771 updateActivityTime, i+1);
1772 }
1773 }
1774 }
1775
Joe Onorato8a9b2202010-02-26 18:56:32 -08001776 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 if (oomAdj) {
1778 updateOomAdjLocked();
1779 }
1780 }
1781
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001782 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001783 boolean oomAdj, boolean updateActivityTime) {
1784 mLruSeq++;
1785 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1786 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001787
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 String processName, int uid) {
1790 if (uid == Process.SYSTEM_UID) {
1791 // The system gets to run in any process. If there are multiple
1792 // processes with the same uid, just pick the first (this
1793 // should never happen).
1794 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1795 processName);
1796 return procs != null ? procs.valueAt(0) : null;
1797 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001798 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 ProcessRecord proc = mProcessNames.get(processName, uid);
1800 return proc;
1801 }
1802
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001804 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001805 try {
1806 if (pm.performDexOpt(packageName)) {
1807 mDidDexOpt = true;
1808 }
1809 } catch (RemoteException e) {
1810 }
1811 }
1812
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001813 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 int transit = mWindowManager.getPendingAppTransition();
1815 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1816 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1817 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1818 }
1819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001822 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1823 boolean isolated) {
1824 ProcessRecord app;
1825 if (!isolated) {
1826 app = getProcessRecordLocked(processName, info.uid);
1827 } else {
1828 // If this is an isolated process, it can't re-use an existing process.
1829 app = null;
1830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 // We don't have to do anything more if:
1832 // (1) There is an existing application record; and
1833 // (2) The caller doesn't think it is dead, OR there is no thread
1834 // object attached to it so we know it couldn't have crashed; and
1835 // (3) There is a pid assigned to it, so it is either starting or
1836 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001837 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 + " app=" + app + " knownToBeDead=" + knownToBeDead
1839 + " thread=" + (app != null ? app.thread : null)
1840 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001841 if (app != null && app.pid > 0) {
1842 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001843 // We already have the app running, or are waiting for it to
1844 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001845 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001846 // If this is a new package in the process, add the package to the list
1847 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001848 return app;
1849 } else {
1850 // An application record is attached to a previous process,
1851 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001852 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001853 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 String hostingNameStr = hostingName != null
1858 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001859
1860 if (!isolated) {
1861 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1862 // If we are in the background, then check to see if this process
1863 // is bad. If so, we will just silently fail.
1864 if (mBadProcesses.get(info.processName, info.uid) != null) {
1865 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1866 + "/" + info.processName);
1867 return null;
1868 }
1869 } else {
1870 // When the user is explicitly starting a process, then clear its
1871 // crash count so that we won't make it bad until they see at
1872 // least one crash dialog again, and make the process good again
1873 // if it had been bad.
1874 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001875 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001876 mProcessCrashTimes.remove(info.processName, info.uid);
1877 if (mBadProcesses.get(info.processName, info.uid) != null) {
1878 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1879 info.processName);
1880 mBadProcesses.remove(info.processName, info.uid);
1881 if (app != null) {
1882 app.bad = false;
1883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885 }
1886 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001889 app = newProcessRecordLocked(null, info, processName, isolated);
1890 if (app == null) {
1891 Slog.w(TAG, "Failed making new process record for "
1892 + processName + "/" + info.uid + " isolated=" + isolated);
1893 return null;
1894 }
1895 mProcessNames.put(processName, app.uid, app);
1896 if (isolated) {
1897 mIsolatedProcesses.put(app.uid, app);
1898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 } else {
1900 // If this is a new package in the process, add the package to the list
1901 app.addPackage(info.packageName);
1902 }
1903
1904 // If the system is not ready yet, then hold off on starting this
1905 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001906 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001907 && !isAllowedWhileBooting(info)
1908 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 if (!mProcessesOnHold.contains(app)) {
1910 mProcessesOnHold.add(app);
1911 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001912 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 return app;
1914 }
1915
1916 startProcessLocked(app, hostingType, hostingNameStr);
1917 return (app.pid != 0) ? app : null;
1918 }
1919
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001920 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1921 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1922 }
1923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 private final void startProcessLocked(ProcessRecord app,
1925 String hostingType, String hostingNameStr) {
1926 if (app.pid > 0 && app.pid != MY_PID) {
1927 synchronized (mPidsSelfLocked) {
1928 mPidsSelfLocked.remove(app.pid);
1929 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1930 }
1931 app.pid = 0;
1932 }
1933
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001934 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1935 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 mProcessesOnHold.remove(app);
1937
1938 updateCpuStats();
1939
1940 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1941 mProcDeaths[0] = 0;
1942
1943 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001944 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001947 if (!app.isolated) {
1948 try {
1949 gids = mContext.getPackageManager().getPackageGids(
1950 app.info.packageName);
1951 } catch (PackageManager.NameNotFoundException e) {
1952 Slog.w(TAG, "Unable to retrieve gids", e);
1953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
1955 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1956 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1957 && mTopComponent != null
1958 && app.processName.equals(mTopComponent.getPackageName())) {
1959 uid = 0;
1960 }
1961 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1962 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1963 uid = 0;
1964 }
1965 }
1966 int debugFlags = 0;
1967 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1968 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001969 // Also turn on CheckJNI for debuggable apps. It's quite
1970 // awkward to turn on otherwise.
1971 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001973 // Run the app in safe mode if its manifest requests so or the
1974 // system is booted in safe mode.
1975 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1976 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001977 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1980 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1981 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001982 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1983 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 if ("1".equals(SystemProperties.get("debug.assert"))) {
1986 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1987 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001988
1989 // Start the process. It will either succeed and return a result containing
1990 // the PID of the new process, or else throw a RuntimeException.
1991 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001992 app.processName, uid, uid, gids, debugFlags,
1993 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1996 synchronized (bs) {
1997 if (bs.isOnBattery()) {
1998 app.batteryStats.incStartsLocked();
1999 }
2000 }
2001
Jeff Brown3f9dd282011-07-08 20:02:19 -07002002 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 app.processName, hostingType,
2004 hostingNameStr != null ? hostingNameStr : "");
2005
2006 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002007 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002010 StringBuilder buf = mStringBuilder;
2011 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 buf.append("Start proc ");
2013 buf.append(app.processName);
2014 buf.append(" for ");
2015 buf.append(hostingType);
2016 if (hostingNameStr != null) {
2017 buf.append(" ");
2018 buf.append(hostingNameStr);
2019 }
2020 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002021 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 buf.append(" uid=");
2023 buf.append(uid);
2024 buf.append(" gids={");
2025 if (gids != null) {
2026 for (int gi=0; gi<gids.length; gi++) {
2027 if (gi != 0) buf.append(", ");
2028 buf.append(gids[gi]);
2029
2030 }
2031 }
2032 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002033 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002034 app.pid = startResult.pid;
2035 app.usingWrapper = startResult.usingWrapper;
2036 app.removed = false;
2037 synchronized (mPidsSelfLocked) {
2038 this.mPidsSelfLocked.put(startResult.pid, app);
2039 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2040 msg.obj = app;
2041 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2042 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
2044 } catch (RuntimeException e) {
2045 // XXX do better error recovery.
2046 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002047 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
2049 }
2050
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002051 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 if (resumed) {
2053 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2054 } else {
2055 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2056 }
2057 }
2058
Amith Yamasani742a6712011-05-04 14:49:28 -07002059 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002060 if (mHeadless) {
2061 // Added because none of the other calls to ensureBootCompleted seem to fire
2062 // when running headless.
2063 ensureBootCompleted();
2064 return false;
2065 }
2066
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002067 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2068 && mTopAction == null) {
2069 // We are running in factory test mode, but unable to find
2070 // the factory test app, so just sit around displaying the
2071 // error message and don't try to start anything.
2072 return false;
2073 }
2074 Intent intent = new Intent(
2075 mTopAction,
2076 mTopData != null ? Uri.parse(mTopData) : null);
2077 intent.setComponent(mTopComponent);
2078 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2079 intent.addCategory(Intent.CATEGORY_HOME);
2080 }
2081 ActivityInfo aInfo =
2082 intent.resolveActivityInfo(mContext.getPackageManager(),
2083 STOCK_PM_FLAGS);
2084 if (aInfo != null) {
2085 intent.setComponent(new ComponentName(
2086 aInfo.applicationInfo.packageName, aInfo.name));
2087 // Don't do this if the home app is currently being
2088 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002089 aInfo = new ActivityInfo(aInfo);
2090 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002091 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2092 aInfo.applicationInfo.uid);
2093 if (app == null || app.instrumentationClass == null) {
2094 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002095 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002096 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002097 }
2098 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002099
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002100 return true;
2101 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002102
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002103 /**
2104 * Starts the "new version setup screen" if appropriate.
2105 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002106 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002107 // Only do this once per boot.
2108 if (mCheckedForSetup) {
2109 return;
2110 }
2111
2112 // We will show this screen if the current one is a different
2113 // version than the last one shown, and we are not running in
2114 // low-level factory test mode.
2115 final ContentResolver resolver = mContext.getContentResolver();
2116 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2117 Settings.Secure.getInt(resolver,
2118 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2119 mCheckedForSetup = true;
2120
2121 // See if we should be showing the platform update setup UI.
2122 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2123 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2124 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2125
2126 // We don't allow third party apps to replace this.
2127 ResolveInfo ri = null;
2128 for (int i=0; ris != null && i<ris.size(); i++) {
2129 if ((ris.get(i).activityInfo.applicationInfo.flags
2130 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2131 ri = ris.get(i);
2132 break;
2133 }
2134 }
2135
2136 if (ri != null) {
2137 String vers = ri.activityInfo.metaData != null
2138 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2139 : null;
2140 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2141 vers = ri.activityInfo.applicationInfo.metaData.getString(
2142 Intent.METADATA_SETUP_VERSION);
2143 }
2144 String lastVers = Settings.Secure.getString(
2145 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2146 if (vers != null && !vers.equals(lastVers)) {
2147 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2148 intent.setComponent(new ComponentName(
2149 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002150 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002151 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002152 }
2153 }
2154 }
2155 }
2156
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002157 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002158 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002159 }
2160
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002161 void enforceNotIsolatedCaller(String caller) {
2162 if (UserId.isIsolated(Binder.getCallingUid())) {
2163 throw new SecurityException("Isolated process not allowed to call " + caller);
2164 }
2165 }
2166
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002167 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002168 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002169 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002170 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2171 }
2172 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002173
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002174 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002175 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2176 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002177 synchronized (this) {
2178 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2179 }
2180 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002183 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002184 synchronized (this) {
2185 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2186 }
2187 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002188
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002189 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002190 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2191 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002192 synchronized (this) {
2193 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002194 }
2195 }
2196
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002197 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002198 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002199 synchronized (this) {
2200 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2201 }
2202 }
2203
2204 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002205 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2206 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002207 synchronized (this) {
2208 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2209 }
2210 }
2211
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002212 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002213 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002214
2215 final int identHash = System.identityHashCode(r);
2216 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218
Jeff Sharkeya4620792011-05-20 15:29:23 -07002219 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2220 int i = mProcessObservers.beginBroadcast();
2221 while (i > 0) {
2222 i--;
2223 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2224 if (observer != null) {
2225 try {
2226 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2227 } catch (RemoteException e) {
2228 }
2229 }
2230 }
2231 mProcessObservers.finishBroadcast();
2232 }
2233
2234 private void dispatchProcessDied(int pid, int uid) {
2235 int i = mProcessObservers.beginBroadcast();
2236 while (i > 0) {
2237 i--;
2238 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2239 if (observer != null) {
2240 try {
2241 observer.onProcessDied(pid, uid);
2242 } catch (RemoteException e) {
2243 }
2244 }
2245 }
2246 mProcessObservers.finishBroadcast();
2247 }
2248
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002249 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002250 final int N = mPendingActivityLaunches.size();
2251 if (N <= 0) {
2252 return;
2253 }
2254 for (int i=0; i<N; i++) {
2255 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002256 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002257 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2258 doResume && i == (N-1));
2259 }
2260 mPendingActivityLaunches.clear();
2261 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002262
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002263 public final int startActivity(IApplicationThread caller,
2264 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2265 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002266 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
Siva Velusamy92a8b222012-03-09 16:24:04 -08002267 boolean openglTrace, String profileFile, ParcelFileDescriptor profileFd,
2268 boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002269 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002270 int userId = 0;
2271 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2272 // Requesting home, set the identity to the current user
2273 // HACK!
2274 userId = mCurrentUserId;
2275 } else {
2276 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2277 // the current user's userId
2278 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2279 userId = 0;
2280 } else {
2281 userId = Binder.getOrigCallingUser();
2282 }
2283 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002284 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07002285 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
Siva Velusamy92a8b222012-03-09 16:24:04 -08002286 debug, openglTrace, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002287 }
2288
2289 public final WaitResult startActivityAndWait(IApplicationThread caller,
2290 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2291 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002292 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
Siva Velusamy92a8b222012-03-09 16:24:04 -08002293 boolean openglTrace, String profileFile, ParcelFileDescriptor profileFd,
2294 boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002295 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002296 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002297 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002298 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002299 grantedUriPermissions, grantedMode, resultTo, resultWho,
Siva Velusamy92a8b222012-03-09 16:24:04 -08002300 requestCode, onlyIfNeeded, debug, openglTrace, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07002301 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002302 return res;
2303 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002304
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002305 public final int startActivityWithConfig(IApplicationThread caller,
2306 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2307 int grantedMode, IBinder resultTo,
2308 String resultWho, int requestCode, boolean onlyIfNeeded,
2309 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002310 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002311 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002312 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07002313 requestCode, onlyIfNeeded,
Siva Velusamy92a8b222012-03-09 16:24:04 -08002314 debug, false, null, null, false, null, config, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002315 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002316 }
2317
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002318 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002319 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002320 IBinder resultTo, String resultWho, int requestCode,
2321 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002322 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002323 // Refuse possible leaked file descriptors
2324 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2325 throw new IllegalArgumentException("File descriptors passed in Intent");
2326 }
2327
2328 IIntentSender sender = intent.getTarget();
2329 if (!(sender instanceof PendingIntentRecord)) {
2330 throw new IllegalArgumentException("Bad PendingIntent object");
2331 }
2332
2333 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002334
2335 synchronized (this) {
2336 // If this is coming from the currently resumed activity, it is
2337 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002338 if (mMainStack.mResumedActivity != null
2339 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002340 Binder.getCallingUid()) {
2341 mAppSwitchesAllowedTime = 0;
2342 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002343 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002344 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002345 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07002346 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002347 }
2348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 public boolean startNextMatchingActivity(IBinder callingActivity,
2350 Intent intent) {
2351 // Refuse possible leaked file descriptors
2352 if (intent != null && intent.hasFileDescriptors() == true) {
2353 throw new IllegalArgumentException("File descriptors passed in Intent");
2354 }
2355
2356 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002357 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2358 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 return false;
2360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 if (r.app == null || r.app.thread == null) {
2362 // The caller is not running... d'oh!
2363 return false;
2364 }
2365 intent = new Intent(intent);
2366 // The caller is not allowed to change the data.
2367 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2368 // And we are resetting to find the next component...
2369 intent.setComponent(null);
2370
2371 ActivityInfo aInfo = null;
2372 try {
2373 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002374 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002376 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377
2378 // Look for the original activity in the list...
2379 final int N = resolves != null ? resolves.size() : 0;
2380 for (int i=0; i<N; i++) {
2381 ResolveInfo rInfo = resolves.get(i);
2382 if (rInfo.activityInfo.packageName.equals(r.packageName)
2383 && rInfo.activityInfo.name.equals(r.info.name)) {
2384 // We found the current one... the next matching is
2385 // after it.
2386 i++;
2387 if (i<N) {
2388 aInfo = resolves.get(i).activityInfo;
2389 }
2390 break;
2391 }
2392 }
2393 } catch (RemoteException e) {
2394 }
2395
2396 if (aInfo == null) {
2397 // Nobody who is next!
2398 return false;
2399 }
2400
2401 intent.setComponent(new ComponentName(
2402 aInfo.applicationInfo.packageName, aInfo.name));
2403 intent.setFlags(intent.getFlags()&~(
2404 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2405 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2406 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2407 Intent.FLAG_ACTIVITY_NEW_TASK));
2408
2409 // Okay now we need to start the new activity, replacing the
2410 // currently running activity. This is a little tricky because
2411 // we want to start the new one as if the current one is finished,
2412 // but not finish the current one first so that there is no flicker.
2413 // And thus...
2414 final boolean wasFinishing = r.finishing;
2415 r.finishing = true;
2416
2417 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002418 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 final String resultWho = r.resultWho;
2420 final int requestCode = r.requestCode;
2421 r.resultTo = null;
2422 if (resultTo != null) {
2423 resultTo.removeResultsLocked(r, resultWho, requestCode);
2424 }
2425
2426 final long origId = Binder.clearCallingIdentity();
2427 // XXX we are not dealing with propagating grantedUriPermissions...
2428 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002429 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002430 r.resolvedType, null, 0, aInfo,
2431 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002432 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 Binder.restoreCallingIdentity(origId);
2434
2435 r.finishing = wasFinishing;
2436 if (res != START_SUCCESS) {
2437 return false;
2438 }
2439 return true;
2440 }
2441 }
2442
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002443 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 Intent intent, String resolvedType, IBinder resultTo,
2445 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002446
2447 // This is so super not safe, that only the system (or okay root)
2448 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002449 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002450 final int callingUid = Binder.getCallingUid();
2451 if (callingUid != 0 && callingUid != Process.myUid()) {
2452 throw new SecurityException(
2453 "startActivityInPackage only available to the system");
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455
Amith Yamasani742a6712011-05-04 14:49:28 -07002456 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Siva Velusamy92a8b222012-03-09 16:24:04 -08002457 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07002458 null, null, false, null, null, userId);
2459 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002460 }
2461
2462 public final int startActivities(IApplicationThread caller,
2463 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002464 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002465 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
2466 Binder.getOrigCallingUser());
2467 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002468 }
2469
2470 public final int startActivitiesInPackage(int uid,
2471 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2472
2473 // This is so super not safe, that only the system (or okay root)
2474 // can do it.
2475 final int callingUid = Binder.getCallingUid();
2476 if (callingUid != 0 && callingUid != Process.myUid()) {
2477 throw new SecurityException(
2478 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002480 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
2481 UserId.getUserId(uid));
2482 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 }
2484
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002485 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002487 // Quick case: check if the top-most recent task is the same.
2488 if (N > 0 && mRecentTasks.get(0) == task) {
2489 return;
2490 }
2491 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 for (int i=0; i<N; i++) {
2493 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002494 if (task.userId == tr.userId
2495 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2496 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 mRecentTasks.remove(i);
2498 i--;
2499 N--;
2500 if (task.intent == null) {
2501 // If the new recent task we are adding is not fully
2502 // specified, then replace it with the existing recent task.
2503 task = tr;
2504 }
2505 }
2506 }
2507 if (N >= MAX_RECENT_TASKS) {
2508 mRecentTasks.remove(N-1);
2509 }
2510 mRecentTasks.add(0, task);
2511 }
2512
2513 public void setRequestedOrientation(IBinder token,
2514 int requestedOrientation) {
2515 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002516 ActivityRecord r = mMainStack.isInStackLocked(token);
2517 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 return;
2519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002521 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002523 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002524 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 if (config != null) {
2526 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002527 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002528 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 }
2530 }
2531 Binder.restoreCallingIdentity(origId);
2532 }
2533 }
2534
2535 public int getRequestedOrientation(IBinder token) {
2536 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002537 ActivityRecord r = mMainStack.isInStackLocked(token);
2538 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2540 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002541 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543 }
2544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 /**
2546 * This is the internal entry point for handling Activity.finish().
2547 *
2548 * @param token The Binder token referencing the Activity we want to finish.
2549 * @param resultCode Result code, if any, from this Activity.
2550 * @param resultData Result data (Intent), if any, from this Activity.
2551 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002552 * @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 -08002553 */
2554 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2555 // Refuse possible leaked file descriptors
2556 if (resultData != null && resultData.hasFileDescriptors() == true) {
2557 throw new IllegalArgumentException("File descriptors passed in Intent");
2558 }
2559
2560 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002561 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002563 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 if (next != null) {
2565 // ask watcher if this is allowed
2566 boolean resumeOK = true;
2567 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002568 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002570 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572
2573 if (!resumeOK) {
2574 return false;
2575 }
2576 }
2577 }
2578 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002579 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 resultData, "app-request");
2581 Binder.restoreCallingIdentity(origId);
2582 return res;
2583 }
2584 }
2585
Dianne Hackborn860755f2010-06-03 18:47:52 -07002586 public final void finishHeavyWeightApp() {
2587 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2588 != PackageManager.PERMISSION_GRANTED) {
2589 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2590 + Binder.getCallingPid()
2591 + ", uid=" + Binder.getCallingUid()
2592 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2593 Slog.w(TAG, msg);
2594 throw new SecurityException(msg);
2595 }
2596
2597 synchronized(this) {
2598 if (mHeavyWeightProcess == null) {
2599 return;
2600 }
2601
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002602 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002603 mHeavyWeightProcess.activities);
2604 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002605 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002606 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002607 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002608 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002609 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002610 null, "finish-heavy");
2611 }
2612 }
2613 }
2614
2615 mHeavyWeightProcess = null;
2616 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2617 }
2618 }
2619
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002620 public void crashApplication(int uid, int initialPid, String packageName,
2621 String message) {
2622 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2623 != PackageManager.PERMISSION_GRANTED) {
2624 String msg = "Permission Denial: crashApplication() from pid="
2625 + Binder.getCallingPid()
2626 + ", uid=" + Binder.getCallingUid()
2627 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2628 Slog.w(TAG, msg);
2629 throw new SecurityException(msg);
2630 }
2631
2632 synchronized(this) {
2633 ProcessRecord proc = null;
2634
2635 // Figure out which process to kill. We don't trust that initialPid
2636 // still has any relation to current pids, so must scan through the
2637 // list.
2638 synchronized (mPidsSelfLocked) {
2639 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2640 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002641 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002642 continue;
2643 }
2644 if (p.pid == initialPid) {
2645 proc = p;
2646 break;
2647 }
2648 for (String str : p.pkgList) {
2649 if (str.equals(packageName)) {
2650 proc = p;
2651 }
2652 }
2653 }
2654 }
2655
2656 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002657 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002658 + " initialPid=" + initialPid
2659 + " packageName=" + packageName);
2660 return;
2661 }
2662
2663 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002664 if (proc.pid == Process.myPid()) {
2665 Log.w(TAG, "crashApplication: trying to crash self!");
2666 return;
2667 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002668 long ident = Binder.clearCallingIdentity();
2669 try {
2670 proc.thread.scheduleCrash(message);
2671 } catch (RemoteException e) {
2672 }
2673 Binder.restoreCallingIdentity(ident);
2674 }
2675 }
2676 }
2677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 public final void finishSubActivity(IBinder token, String resultWho,
2679 int requestCode) {
2680 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002681 ActivityRecord self = mMainStack.isInStackLocked(token);
2682 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 return;
2684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685
2686 final long origId = Binder.clearCallingIdentity();
2687
2688 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002689 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2690 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 if (r.resultTo == self && r.requestCode == requestCode) {
2692 if ((r.resultWho == null && resultWho == null) ||
2693 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002694 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 Activity.RESULT_CANCELED, null, "request-sub");
2696 }
2697 }
2698 }
2699
2700 Binder.restoreCallingIdentity(origId);
2701 }
2702 }
2703
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002704 public boolean willActivityBeVisible(IBinder token) {
2705 synchronized(this) {
2706 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002707 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2708 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002709 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002710 return true;
2711 }
2712 if (r.fullscreen && !r.finishing) {
2713 return false;
2714 }
2715 }
2716 return true;
2717 }
2718 }
2719
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002720 public void overridePendingTransition(IBinder token, String packageName,
2721 int enterAnim, int exitAnim) {
2722 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002723 ActivityRecord self = mMainStack.isInStackLocked(token);
2724 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002725 return;
2726 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002727
2728 final long origId = Binder.clearCallingIdentity();
2729
2730 if (self.state == ActivityState.RESUMED
2731 || self.state == ActivityState.PAUSING) {
2732 mWindowManager.overridePendingAppTransition(packageName,
2733 enterAnim, exitAnim);
2734 }
2735
2736 Binder.restoreCallingIdentity(origId);
2737 }
2738 }
2739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 * Main function for removing an existing process from the activity manager
2742 * as a result of that process going away. Clears out all connections
2743 * to the process.
2744 */
2745 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002746 boolean restarting, boolean allowRestart) {
2747 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002749 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 }
2751
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002752 if (mProfileProc == app) {
2753 clearProfilerLocked();
2754 }
2755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002757 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2758 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2759 mMainStack.mPausingActivity = null;
2760 }
2761 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2762 mMainStack.mLastPausedActivity = null;
2763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764
2765 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767
2768 boolean atTop = true;
2769 boolean hasVisibleActivities = false;
2770
2771 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002772 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002773 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 TAG, "Removing app " + app + " from history with " + i + " entries");
2775 while (i > 0) {
2776 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002778 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2780 if (r.app == app) {
2781 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002782 if (ActivityStack.DEBUG_ADD_REMOVE) {
2783 RuntimeException here = new RuntimeException("here");
2784 here.fillInStackTrace();
2785 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2786 + ": haveState=" + r.haveState
2787 + " stateNotNeeded=" + r.stateNotNeeded
2788 + " finishing=" + r.finishing
2789 + " state=" + r.state, here);
2790 }
2791 if (!r.finishing) {
2792 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002793 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2794 System.identityHashCode(r),
2795 r.task.taskId, r.shortComponentName,
2796 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002797 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002798 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799
2800 } else {
2801 // We have the current state for this activity, so
2802 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002803 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 TAG, "Keeping entry, setting app to null");
2805 if (r.visible) {
2806 hasVisibleActivities = true;
2807 }
2808 r.app = null;
2809 r.nowVisible = false;
2810 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002811 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2812 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 r.icicle = null;
2814 }
2815 }
2816
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002817 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 }
2819 atTop = false;
2820 }
2821
2822 app.activities.clear();
2823
2824 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002825 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 + " running instrumentation " + app.instrumentationClass);
2827 Bundle info = new Bundle();
2828 info.putString("shortMsg", "Process crashed.");
2829 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2830 }
2831
2832 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002833 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 // If there was nothing to resume, and we are not already
2835 // restarting this process, but there is a visible activity that
2836 // is hosted by the process... then make sure all visible
2837 // activities are running, taking care of restarting this
2838 // process.
2839 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002840 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 }
2842 }
2843 }
2844 }
2845
2846 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2847 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002849 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2850 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2852 return i;
2853 }
2854 }
2855 return -1;
2856 }
2857
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002858 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 IApplicationThread thread) {
2860 if (thread == null) {
2861 return null;
2862 }
2863
2864 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002865 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 }
2867
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 IApplicationThread thread) {
2870
2871 mProcDeaths[0]++;
2872
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002873 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2874 synchronized (stats) {
2875 stats.noteProcessDiedLocked(app.info.uid, pid);
2876 }
2877
Magnus Edlund7bb25812010-02-24 15:45:06 +01002878 // Clean up already done if the process has been re-started.
2879 if (app.pid == pid && app.thread != null &&
2880 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002881 if (!app.killedBackground) {
2882 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2883 + ") has died.");
2884 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002885 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002886 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 TAG, "Dying app: " + app + ", pid: " + pid
2888 + ", thread: " + thread.asBinder());
2889 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002890 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891
2892 if (doLowMem) {
2893 // If there are no longer any background processes running,
2894 // and the app that died was not running instrumentation,
2895 // then tell everyone we are now low on memory.
2896 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002897 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2898 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002899 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 haveBg = true;
2901 break;
2902 }
2903 }
2904
2905 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002906 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002907 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002908 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2909 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002910 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002911 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2912 // The low memory report is overriding any current
2913 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002914 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002915 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002916 rec.lastRequestedGc = 0;
2917 } else {
2918 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002920 rec.reportLowMemory = true;
2921 rec.lastLowMemory = now;
2922 mProcessesToGc.remove(rec);
2923 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
2925 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002926 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002927 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002930 } else if (app.pid != pid) {
2931 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002932 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002933 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002934 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002935 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002936 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 + thread.asBinder());
2938 }
2939 }
2940
Dan Egnor42471dd2010-01-07 17:25:22 -08002941 /**
2942 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002943 * @param clearTraces causes the dump file to be erased prior to the new
2944 * traces being written, if true; when false, the new traces will be
2945 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002946 * @param firstPids of dalvik VM processes to dump stack traces for first
2947 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002948 * @return file containing stack traces, or null if no dump file is configured
2949 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002950 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2951 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002952 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2953 if (tracesPath == null || tracesPath.length() == 0) {
2954 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002956
2957 File tracesFile = new File(tracesPath);
2958 try {
2959 File tracesDir = tracesFile.getParentFile();
2960 if (!tracesDir.exists()) tracesFile.mkdirs();
2961 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2962
Christopher Tate6ee412d2010-05-28 12:01:56 -07002963 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002964 tracesFile.createNewFile();
2965 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2966 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002967 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002968 return null;
2969 }
2970
2971 // Use a FileObserver to detect when traces finish writing.
2972 // The order of traces is considered important to maintain for legibility.
2973 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2974 public synchronized void onEvent(int event, String path) { notify(); }
2975 };
2976
2977 try {
2978 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002979
2980 // First collect all of the stacks of the most important pids.
2981 try {
2982 int num = firstPids.size();
2983 for (int i = 0; i < num; i++) {
2984 synchronized (observer) {
2985 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2986 observer.wait(200); // Wait for write-close, give up after 200msec
2987 }
2988 }
2989 } catch (InterruptedException e) {
2990 Log.wtf(TAG, e);
2991 }
2992
2993 // Next measure CPU usage.
2994 if (processStats != null) {
2995 processStats.init();
2996 System.gc();
2997 processStats.update();
2998 try {
2999 synchronized (processStats) {
3000 processStats.wait(500); // measure over 1/2 second.
3001 }
3002 } catch (InterruptedException e) {
3003 }
3004 processStats.update();
3005
3006 // We'll take the stack crawls of just the top apps using CPU.
3007 final int N = processStats.countWorkingStats();
3008 int numProcs = 0;
3009 for (int i=0; i<N && numProcs<5; i++) {
3010 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3011 if (lastPids.indexOfKey(stats.pid) >= 0) {
3012 numProcs++;
3013 try {
3014 synchronized (observer) {
3015 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3016 observer.wait(200); // Wait for write-close, give up after 200msec
3017 }
3018 } catch (InterruptedException e) {
3019 Log.wtf(TAG, e);
3020 }
3021
3022 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003023 }
3024 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003025
3026 return tracesFile;
3027
Dan Egnor42471dd2010-01-07 17:25:22 -08003028 } finally {
3029 observer.stopWatching();
3030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003033 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3034 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003035 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3036 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3037
Dianne Hackborn287952c2010-09-22 22:34:31 -07003038 if (mController != null) {
3039 try {
3040 // 0 == continue, -1 = kill process immediately
3041 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3042 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3043 } catch (RemoteException e) {
3044 mController = null;
3045 }
3046 }
3047
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003048 long anrTime = SystemClock.uptimeMillis();
3049 if (MONITOR_CPU_USAGE) {
3050 updateCpuStatsNow();
3051 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003052
3053 synchronized (this) {
3054 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3055 if (mShuttingDown) {
3056 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3057 return;
3058 } else if (app.notResponding) {
3059 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3060 return;
3061 } else if (app.crashing) {
3062 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3063 return;
3064 }
3065
3066 // In case we come through here for the same app before completing
3067 // this one, mark as anring now so we will bail out.
3068 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003069
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003070 // Log the ANR to the event log.
3071 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3072 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003073
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003074 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003075 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003076
3077 int parentPid = app.pid;
3078 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003079 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003080
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003081 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003082
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003083 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3084 ProcessRecord r = mLruProcesses.get(i);
3085 if (r != null && r.thread != null) {
3086 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003087 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3088 if (r.persistent) {
3089 firstPids.add(pid);
3090 } else {
3091 lastPids.put(pid, Boolean.TRUE);
3092 }
3093 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 }
3096 }
3097
Dan Egnor42471dd2010-01-07 17:25:22 -08003098 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003099 StringBuilder info = mStringBuilder;
3100 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003101 info.append("ANR in ").append(app.processName);
3102 if (activity != null && activity.shortComponentName != null) {
3103 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003104 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003105 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003107 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003109 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003110 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112
Dianne Hackborn287952c2010-09-22 22:34:31 -07003113 final ProcessStats processStats = new ProcessStats(true);
3114
3115 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3116
Dan Egnor42471dd2010-01-07 17:25:22 -08003117 String cpuInfo = null;
3118 if (MONITOR_CPU_USAGE) {
3119 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003120 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003121 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003122 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003123 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003124 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 }
3126
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003127 info.append(processStats.printCurrentState(anrTime));
3128
Joe Onorato8a9b2202010-02-26 18:56:32 -08003129 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003130 if (tracesFile == null) {
3131 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3132 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3133 }
3134
Jeff Sharkeya353d262011-10-28 11:12:06 -07003135 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3136 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003137
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003138 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003140 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3141 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003143 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3144 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
3146 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003147 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 }
3149 }
3150
Dan Egnor42471dd2010-01-07 17:25:22 -08003151 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3152 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3153 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003154
3155 synchronized (this) {
3156 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003157 Slog.w(TAG, "Killing " + app + ": background ANR");
3158 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3159 app.processName, app.setAdj, "background ANR");
3160 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003161 return;
3162 }
3163
3164 // Set the app's notResponding state, and look up the errorReportReceiver
3165 makeAppNotRespondingLocked(app,
3166 activity != null ? activity.shortComponentName : null,
3167 annotation != null ? "ANR " + annotation : "ANR",
3168 info.toString());
3169
3170 // Bring up the infamous App Not Responding dialog
3171 Message msg = Message.obtain();
3172 HashMap map = new HashMap();
3173 msg.what = SHOW_NOT_RESPONDING_MSG;
3174 msg.obj = map;
3175 map.put("app", app);
3176 if (activity != null) {
3177 map.put("activity", activity);
3178 }
3179
3180 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 }
3183
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003184 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3185 if (!mLaunchWarningShown) {
3186 mLaunchWarningShown = true;
3187 mHandler.post(new Runnable() {
3188 @Override
3189 public void run() {
3190 synchronized (ActivityManagerService.this) {
3191 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3192 d.show();
3193 mHandler.postDelayed(new Runnable() {
3194 @Override
3195 public void run() {
3196 synchronized (ActivityManagerService.this) {
3197 d.dismiss();
3198 mLaunchWarningShown = false;
3199 }
3200 }
3201 }, 4000);
3202 }
3203 }
3204 });
3205 }
3206 }
3207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003209 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003210 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 int uid = Binder.getCallingUid();
3212 int pid = Binder.getCallingPid();
3213 long callingId = Binder.clearCallingIdentity();
3214 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003215 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 int pkgUid = -1;
3217 synchronized(this) {
3218 try {
3219 pkgUid = pm.getPackageUid(packageName);
3220 } catch (RemoteException e) {
3221 }
3222 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003223 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 return false;
3225 }
3226 if (uid == pkgUid || checkComponentPermission(
3227 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003228 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003230 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 } else {
3232 throw new SecurityException(pid+" does not have permission:"+
3233 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3234 "for process:"+packageName);
3235 }
3236 }
3237
3238 try {
3239 //clear application user data
3240 pm.clearApplicationUserData(packageName, observer);
3241 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3242 Uri.fromParts("package", packageName, null));
3243 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003244 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003245 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 } catch (RemoteException e) {
3247 }
3248 } finally {
3249 Binder.restoreCallingIdentity(callingId);
3250 }
3251 return true;
3252 }
3253
Dianne Hackborn03abb812010-01-04 18:43:19 -08003254 public void killBackgroundProcesses(final String packageName) {
3255 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3256 != PackageManager.PERMISSION_GRANTED &&
3257 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3258 != PackageManager.PERMISSION_GRANTED) {
3259 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 + Binder.getCallingPid()
3261 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003262 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003263 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 throw new SecurityException(msg);
3265 }
3266
3267 long callingId = Binder.clearCallingIdentity();
3268 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003269 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 int pkgUid = -1;
3271 synchronized(this) {
3272 try {
3273 pkgUid = pm.getPackageUid(packageName);
3274 } catch (RemoteException e) {
3275 }
3276 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003277 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 return;
3279 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003280 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003281 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3282 }
3283 } finally {
3284 Binder.restoreCallingIdentity(callingId);
3285 }
3286 }
3287
3288 public void killAllBackgroundProcesses() {
3289 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3290 != PackageManager.PERMISSION_GRANTED) {
3291 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3292 + Binder.getCallingPid()
3293 + ", uid=" + Binder.getCallingUid()
3294 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3295 Slog.w(TAG, msg);
3296 throw new SecurityException(msg);
3297 }
3298
3299 long callingId = Binder.clearCallingIdentity();
3300 try {
3301 synchronized(this) {
3302 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3303 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3304 final int NA = apps.size();
3305 for (int ia=0; ia<NA; ia++) {
3306 ProcessRecord app = apps.valueAt(ia);
3307 if (app.persistent) {
3308 // we don't kill persistent processes
3309 continue;
3310 }
3311 if (app.removed) {
3312 procs.add(app);
3313 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3314 app.removed = true;
3315 procs.add(app);
3316 }
3317 }
3318 }
3319
3320 int N = procs.size();
3321 for (int i=0; i<N; i++) {
3322 removeProcessLocked(procs.get(i), false, true, "kill all background");
3323 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003324 }
3325 } finally {
3326 Binder.restoreCallingIdentity(callingId);
3327 }
3328 }
3329
3330 public void forceStopPackage(final String packageName) {
3331 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3332 != PackageManager.PERMISSION_GRANTED) {
3333 String msg = "Permission Denial: forceStopPackage() from pid="
3334 + Binder.getCallingPid()
3335 + ", uid=" + Binder.getCallingUid()
3336 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003337 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003338 throw new SecurityException(msg);
3339 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003340 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003341 long callingId = Binder.clearCallingIdentity();
3342 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003343 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003344 int pkgUid = -1;
3345 synchronized(this) {
3346 try {
3347 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003348 // Convert the uid to the one for the calling user
3349 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003350 } catch (RemoteException e) {
3351 }
3352 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003353 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003354 return;
3355 }
3356 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003357 try {
3358 pm.setPackageStoppedState(packageName, true);
3359 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003360 } catch (IllegalArgumentException e) {
3361 Slog.w(TAG, "Failed trying to unstop package "
3362 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 }
3365 } finally {
3366 Binder.restoreCallingIdentity(callingId);
3367 }
3368 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003369
3370 /*
3371 * The pkg name and uid have to be specified.
3372 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3373 */
3374 public void killApplicationWithUid(String pkg, int uid) {
3375 if (pkg == null) {
3376 return;
3377 }
3378 // Make sure the uid is valid.
3379 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003380 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003381 return;
3382 }
3383 int callerUid = Binder.getCallingUid();
3384 // Only the system server can kill an application
3385 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003386 // Post an aysnc message to kill the application
3387 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3388 msg.arg1 = uid;
3389 msg.arg2 = 0;
3390 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003391 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003392 } else {
3393 throw new SecurityException(callerUid + " cannot kill pkg: " +
3394 pkg);
3395 }
3396 }
3397
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003398 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003399 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003400 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003401 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003402 if (reason != null) {
3403 intent.putExtra("reason", reason);
3404 }
3405
3406 final int uid = Binder.getCallingUid();
3407 final long origId = Binder.clearCallingIdentity();
3408 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003409 mWindowManager.closeSystemDialogs(reason);
3410
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003411 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003412 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003413 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003414 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003415 Activity.RESULT_CANCELED, null, "close-sys");
3416 }
3417 }
3418
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003419 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003420 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003421 }
3422 Binder.restoreCallingIdentity(origId);
3423 }
3424
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003425 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003426 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003427 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003428 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3429 for (int i=pids.length-1; i>=0; i--) {
3430 infos[i] = new Debug.MemoryInfo();
3431 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003432 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003433 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003434 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003435
Dianne Hackbornb437e092011-08-05 17:50:29 -07003436 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003437 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003438 long[] pss = new long[pids.length];
3439 for (int i=pids.length-1; i>=0; i--) {
3440 pss[i] = Debug.getPss(pids[i]);
3441 }
3442 return pss;
3443 }
3444
Christopher Tate5e1ab332009-09-01 20:32:49 -07003445 public void killApplicationProcess(String processName, int uid) {
3446 if (processName == null) {
3447 return;
3448 }
3449
3450 int callerUid = Binder.getCallingUid();
3451 // Only the system server can kill an application
3452 if (callerUid == Process.SYSTEM_UID) {
3453 synchronized (this) {
3454 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003455 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003456 try {
3457 app.thread.scheduleSuicide();
3458 } catch (RemoteException e) {
3459 // If the other end already died, then our work here is done.
3460 }
3461 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003462 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003463 + processName + " / " + uid);
3464 }
3465 }
3466 } else {
3467 throw new SecurityException(callerUid + " cannot kill app process: " +
3468 processName);
3469 }
3470 }
3471
Dianne Hackborn03abb812010-01-04 18:43:19 -08003472 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003473 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3475 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003476 if (!mProcessesReady) {
3477 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 intent.putExtra(Intent.EXTRA_UID, uid);
3480 broadcastIntentLocked(null, null, intent,
3481 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003482 false, false,
3483 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 }
3485
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003486 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003487 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003488 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003489 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490
Dianne Hackborn03abb812010-01-04 18:43:19 -08003491 // Remove all processes this package may have touched: all with the
3492 // same UID (except for the system or root user), and all whose name
3493 // matches the package name.
3494 final String procNamePrefix = packageName + ":";
3495 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3496 final int NA = apps.size();
3497 for (int ia=0; ia<NA; ia++) {
3498 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003499 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003500 // we don't kill persistent processes
3501 continue;
3502 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003503 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003504 if (doit) {
3505 procs.add(app);
3506 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003507 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3508 || app.processName.equals(packageName)
3509 || app.processName.startsWith(procNamePrefix)) {
3510 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003511 if (!doit) {
3512 return true;
3513 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003514 app.removed = true;
3515 procs.add(app);
3516 }
3517 }
3518 }
3519 }
3520
3521 int N = procs.size();
3522 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003523 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003524 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003525 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003526 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003527
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003528 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003529 boolean callerWillRestart, boolean purgeCache, boolean doit,
3530 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003531 int i;
3532 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 if (uid < 0) {
3535 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003536 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 } catch (RemoteException e) {
3538 }
3539 }
3540
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003541 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003542 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003543
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003544 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3545 while (badApps.hasNext()) {
3546 SparseArray<Long> ba = badApps.next();
3547 if (ba.get(uid) != null) {
3548 badApps.remove();
3549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 }
3551 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003552
3553 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003554 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003556 TaskRecord lastTask = null;
3557 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003558 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003559 final boolean samePackage = r.packageName.equals(name);
3560 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003561 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003562 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003563 if (r.finishing) {
3564 // If this activity is just finishing, then it is not
3565 // interesting as far as something to stop.
3566 continue;
3567 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003568 return true;
3569 }
3570 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003571 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003572 if (samePackage) {
3573 if (r.app != null) {
3574 r.app.removed = true;
3575 }
3576 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003578 lastTask = r.task;
3579 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3580 null, "force-stop")) {
3581 i--;
3582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 }
3584 }
3585
3586 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003587 int userId = UserId.getUserId(uid);
3588 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003589 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003590 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003591 if (!doit) {
3592 return true;
3593 }
3594 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003595 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 if (service.app != null) {
3597 service.app.removed = true;
3598 }
3599 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003600 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 services.add(service);
3602 }
3603 }
3604
3605 N = services.size();
3606 for (i=0; i<N; i++) {
3607 bringDownServiceLocked(services.get(i), true);
3608 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003609
3610 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003611 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003612 if (provider.info.packageName.equals(name)
3613 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3614 if (!doit) {
3615 return true;
3616 }
3617 didSomething = true;
3618 providers.add(provider);
3619 }
3620 }
3621
3622 N = providers.size();
3623 for (i=0; i<N; i++) {
3624 removeDyingProviderLocked(null, providers.get(i));
3625 }
3626
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003627 if (doit) {
3628 if (purgeCache) {
3629 AttributeCache ac = AttributeCache.instance();
3630 if (ac != null) {
3631 ac.removePackage(name);
3632 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003633 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003634 if (mBooted) {
3635 mMainStack.resumeTopActivityLocked(null);
3636 mMainStack.scheduleIdleLocked();
3637 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003638 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003639
3640 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003643 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003644 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003646 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003647 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003648 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 + "/" + uid + ")");
3650
3651 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003652 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003653 if (mHeavyWeightProcess == app) {
3654 mHeavyWeightProcess = null;
3655 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 boolean needRestart = false;
3658 if (app.pid > 0 && app.pid != MY_PID) {
3659 int pid = app.pid;
3660 synchronized (mPidsSelfLocked) {
3661 mPidsSelfLocked.remove(pid);
3662 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3663 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003664 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003665 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003666 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003667 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003669 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003671 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 } else {
3673 needRestart = true;
3674 }
3675 }
3676 } else {
3677 mRemovedProcesses.add(app);
3678 }
3679
3680 return needRestart;
3681 }
3682
3683 private final void processStartTimedOutLocked(ProcessRecord app) {
3684 final int pid = app.pid;
3685 boolean gone = false;
3686 synchronized (mPidsSelfLocked) {
3687 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3688 if (knownApp != null && knownApp.thread == null) {
3689 mPidsSelfLocked.remove(pid);
3690 gone = true;
3691 }
3692 }
3693
3694 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003695 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003696 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003697 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003698 mProcessNames.remove(app.processName, app.uid);
3699 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003700 if (mHeavyWeightProcess == app) {
3701 mHeavyWeightProcess = null;
3702 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3703 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003704 // Take care of any launching providers waiting for this process.
3705 checkAppInLaunchingProvidersLocked(app, true);
3706 // Take care of any services that are waiting for the process.
3707 for (int i=0; i<mPendingServices.size(); i++) {
3708 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003709 if ((app.uid == sr.appInfo.uid
3710 && app.processName.equals(sr.processName))
3711 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003712 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003713 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003714 mPendingServices.remove(i);
3715 i--;
3716 bringDownServiceLocked(sr, true);
3717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003719 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3720 app.processName, app.setAdj, "start timeout");
3721 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003722 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003723 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003724 try {
3725 IBackupManager bm = IBackupManager.Stub.asInterface(
3726 ServiceManager.getService(Context.BACKUP_SERVICE));
3727 bm.agentDisconnected(app.info.packageName);
3728 } catch (RemoteException e) {
3729 // Can't happen; the backup manager is local
3730 }
3731 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003732 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003733 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003734 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003737 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
3739 }
3740
3741 private final boolean attachApplicationLocked(IApplicationThread thread,
3742 int pid) {
3743
3744 // Find the application record that is being attached... either via
3745 // the pid if we are running in multiple processes, or just pull the
3746 // next app record if we are emulating process with anonymous threads.
3747 ProcessRecord app;
3748 if (pid != MY_PID && pid >= 0) {
3749 synchronized (mPidsSelfLocked) {
3750 app = mPidsSelfLocked.get(pid);
3751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 } else {
3753 app = null;
3754 }
3755
3756 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003757 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003759 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003761 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 } else {
3763 try {
3764 thread.scheduleExit();
3765 } catch (Exception e) {
3766 // Ignore exceptions.
3767 }
3768 }
3769 return false;
3770 }
3771
3772 // If this application record is still attached to a previous
3773 // process, clean it up now.
3774 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003775 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 }
3777
3778 // Tell the process all about itself.
3779
Joe Onorato8a9b2202010-02-26 18:56:32 -08003780 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 TAG, "Binding process pid " + pid + " to record " + app);
3782
3783 String processName = app.processName;
3784 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003785 AppDeathRecipient adr = new AppDeathRecipient(
3786 app, pid, thread);
3787 thread.asBinder().linkToDeath(adr, 0);
3788 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 } catch (RemoteException e) {
3790 app.resetPackageList();
3791 startProcessLocked(app, "link fail", processName);
3792 return false;
3793 }
3794
Doug Zongker2bec3d42009-12-04 12:52:44 -08003795 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796
3797 app.thread = thread;
3798 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003799 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3800 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 app.forcingToForeground = null;
3802 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003803 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 app.debugging = false;
3805
3806 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3807
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003808 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003809 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003811 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003812 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003813 }
3814
Joe Onorato8a9b2202010-02-26 18:56:32 -08003815 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 TAG, "New app record " + app
3817 + " thread=" + thread.asBinder() + " pid=" + pid);
3818 try {
3819 int testMode = IApplicationThread.DEBUG_OFF;
3820 if (mDebugApp != null && mDebugApp.equals(processName)) {
3821 testMode = mWaitForDebugger
3822 ? IApplicationThread.DEBUG_WAIT
3823 : IApplicationThread.DEBUG_ON;
3824 app.debugging = true;
3825 if (mDebugTransient) {
3826 mDebugApp = mOrigDebugApp;
3827 mWaitForDebugger = mOrigWaitForDebugger;
3828 }
3829 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003830 String profileFile = app.instrumentationProfileFile;
3831 ParcelFileDescriptor profileFd = null;
3832 boolean profileAutoStop = false;
3833 if (mProfileApp != null && mProfileApp.equals(processName)) {
3834 mProfileProc = app;
3835 profileFile = mProfileFile;
3836 profileFd = mProfileFd;
3837 profileAutoStop = mAutoStopProfiler;
3838 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003839 boolean enableOpenGlTrace = false;
3840 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3841 enableOpenGlTrace = true;
3842 mOpenGlTraceApp = null;
3843 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003844
Christopher Tate181fafa2009-05-14 11:12:14 -07003845 // If the app is being launched for restore or full backup, set it up specially
3846 boolean isRestrictedBackupMode = false;
3847 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3848 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003849 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003850 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3851 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003852
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003853 ensurePackageDexOpt(app.instrumentationInfo != null
3854 ? app.instrumentationInfo.packageName
3855 : app.info.packageName);
3856 if (app.instrumentationClass != null) {
3857 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003858 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003859 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003860 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003861 ApplicationInfo appInfo = app.instrumentationInfo != null
3862 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003863 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003864 if (profileFd != null) {
3865 profileFd = profileFd.dup();
3866 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003867 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003868 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003869 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3870 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003871 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003872 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003873 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003874 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 } catch (Exception e) {
3876 // todo: Yikes! What should we do? For now we will try to
3877 // start another process, but that could easily get us in
3878 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003879 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880
3881 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003882 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 startProcessLocked(app, "bind fail", processName);
3884 return false;
3885 }
3886
3887 // Remove this record from the list of starting applications.
3888 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003889 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3890 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 mProcessesOnHold.remove(app);
3892
3893 boolean badApp = false;
3894 boolean didSomething = false;
3895
3896 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003897 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003898 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003899 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 && processName.equals(hr.processName)) {
3901 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003902 if (mHeadless) {
3903 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3904 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 didSomething = true;
3906 }
3907 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003908 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 + hr.intent.getComponent().flattenToShortString(), e);
3910 badApp = true;
3911 }
3912 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003913 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 }
3915 }
3916
3917 // Find any services that should be running in this process...
3918 if (!badApp && mPendingServices.size() > 0) {
3919 ServiceRecord sr = null;
3920 try {
3921 for (int i=0; i<mPendingServices.size(); i++) {
3922 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003923 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3924 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 continue;
3926 }
3927
3928 mPendingServices.remove(i);
3929 i--;
3930 realStartServiceLocked(sr, app);
3931 didSomething = true;
3932 }
3933 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003934 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 + sr.shortName, e);
3936 badApp = true;
3937 }
3938 }
3939
Christopher Tatef46723b2012-01-26 14:19:24 -08003940 // Check if a next-broadcast receiver is in this process...
3941 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003943 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003945 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 }
3948 }
3949
Christopher Tate181fafa2009-05-14 11:12:14 -07003950 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003951 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003952 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003953 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003954 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003955 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3956 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3957 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003958 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003959 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003960 e.printStackTrace();
3961 }
3962 }
3963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 if (badApp) {
3965 // todo: Also need to kill application to deal with all
3966 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003967 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 return false;
3969 }
3970
3971 if (!didSomething) {
3972 updateOomAdjLocked();
3973 }
3974
3975 return true;
3976 }
3977
3978 public final void attachApplication(IApplicationThread thread) {
3979 synchronized (this) {
3980 int callingPid = Binder.getCallingPid();
3981 final long origId = Binder.clearCallingIdentity();
3982 attachApplicationLocked(thread, callingPid);
3983 Binder.restoreCallingIdentity(origId);
3984 }
3985 }
3986
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003987 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003989 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3990 if (stopProfiling) {
3991 synchronized (this) {
3992 if (mProfileProc == r.app) {
3993 if (mProfileFd != null) {
3994 try {
3995 mProfileFd.close();
3996 } catch (IOException e) {
3997 }
3998 clearProfilerLocked();
3999 }
4000 }
4001 }
4002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 Binder.restoreCallingIdentity(origId);
4004 }
4005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004007 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004008 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 mWindowManager.enableScreenAfterBoot();
4010 }
4011
Dianne Hackborn661cd522011-08-22 00:26:20 -07004012 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004013 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004014 mWindowManager.showBootMessage(msg, always);
4015 }
4016
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004017 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004018 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004019 synchronized (this) {
4020 mMainStack.dismissKeyguardOnNextActivityLocked();
4021 }
4022 }
4023
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004024 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004025 IntentFilter pkgFilter = new IntentFilter();
4026 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4027 pkgFilter.addDataScheme("package");
4028 mContext.registerReceiver(new BroadcastReceiver() {
4029 @Override
4030 public void onReceive(Context context, Intent intent) {
4031 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4032 if (pkgs != null) {
4033 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004034 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004035 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004036 setResultCode(Activity.RESULT_OK);
4037 return;
4038 }
4039 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004040 }
4041 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004042 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004043 }, pkgFilter);
4044
4045 synchronized (this) {
4046 // Ensure that any processes we had put on hold are now started
4047 // up.
4048 final int NP = mProcessesOnHold.size();
4049 if (NP > 0) {
4050 ArrayList<ProcessRecord> procs =
4051 new ArrayList<ProcessRecord>(mProcessesOnHold);
4052 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004053 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4054 + procs.get(ip));
4055 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004056 }
4057 }
4058
4059 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004060 // Start looking for apps that are abusing wake locks.
4061 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004062 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004063 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004064 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004065 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004066 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004067 broadcastIntentLocked(null, null,
4068 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4069 null, null, 0, null, null,
4070 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004071 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004072 }
4073 }
4074 }
4075
4076 final void ensureBootCompleted() {
4077 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004078 boolean enableScreen;
4079 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004080 booting = mBooting;
4081 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004082 enableScreen = !mBooted;
4083 mBooted = true;
4084 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004085
4086 if (booting) {
4087 finishBooting();
4088 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004089
4090 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004091 enableScreenAfterBoot();
4092 }
4093 }
4094
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004095 public final void activityPaused(IBinder token) {
4096 final long origId = Binder.clearCallingIdentity();
4097 mMainStack.activityPaused(token, false);
4098 Binder.restoreCallingIdentity(origId);
4099 }
4100
4101 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4102 CharSequence description) {
4103 if (localLOGV) Slog.v(
4104 TAG, "Activity stopped: token=" + token);
4105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 // Refuse possible leaked file descriptors
4107 if (icicle != null && icicle.hasFileDescriptors()) {
4108 throw new IllegalArgumentException("File descriptors passed in Bundle");
4109 }
4110
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004111 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112
4113 final long origId = Binder.clearCallingIdentity();
4114
4115 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004116 r = mMainStack.isInStackLocked(token);
4117 if (r != null) {
4118 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 }
4120 }
4121
4122 if (r != null) {
4123 sendPendingThumbnail(r, null, null, null, false);
4124 }
4125
4126 trimApplications();
4127
4128 Binder.restoreCallingIdentity(origId);
4129 }
4130
4131 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004132 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004133 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
4135
4136 public String getCallingPackage(IBinder token) {
4137 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004138 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004139 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 }
4141 }
4142
4143 public ComponentName getCallingActivity(IBinder token) {
4144 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004145 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 return r != null ? r.intent.getComponent() : null;
4147 }
4148 }
4149
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004150 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004151 ActivityRecord r = mMainStack.isInStackLocked(token);
4152 if (r == null) {
4153 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004155 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 }
4157
4158 public ComponentName getActivityClassForToken(IBinder token) {
4159 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004160 ActivityRecord r = mMainStack.isInStackLocked(token);
4161 if (r == null) {
4162 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004164 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 }
4166 }
4167
4168 public String getPackageForToken(IBinder token) {
4169 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004170 ActivityRecord r = mMainStack.isInStackLocked(token);
4171 if (r == null) {
4172 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004174 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 }
4176 }
4177
4178 public IIntentSender getIntentSender(int type,
4179 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004180 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004181 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004183 if (intents != null) {
4184 if (intents.length < 1) {
4185 throw new IllegalArgumentException("Intents array length must be >= 1");
4186 }
4187 for (int i=0; i<intents.length; i++) {
4188 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004189 if (intent != null) {
4190 if (intent.hasFileDescriptors()) {
4191 throw new IllegalArgumentException("File descriptors passed in Intent");
4192 }
4193 if (type == INTENT_SENDER_BROADCAST &&
4194 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4195 throw new IllegalArgumentException(
4196 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4197 }
4198 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004199 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004200 }
4201 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004202 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004203 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004204 }
4205 }
4206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 synchronized(this) {
4208 int callingUid = Binder.getCallingUid();
4209 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004210 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004211 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004213 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 String msg = "Permission Denial: getIntentSender() from pid="
4215 + Binder.getCallingPid()
4216 + ", uid=" + Binder.getCallingUid()
4217 + ", (need uid=" + uid + ")"
4218 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004219 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 throw new SecurityException(msg);
4221 }
4222 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004223
Amith Yamasani742a6712011-05-04 14:49:28 -07004224 if (DEBUG_MU)
4225 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4226 + Binder.getOrigCallingUid());
4227 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004228 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 } catch (RemoteException e) {
4231 throw new SecurityException(e);
4232 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004233 }
4234 }
4235
4236 IIntentSender getIntentSenderLocked(int type,
4237 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004238 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004239 if (DEBUG_MU)
4240 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004241 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004242 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004243 activity = mMainStack.isInStackLocked(token);
4244 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004245 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004247 if (activity.finishing) {
4248 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004250 }
4251
4252 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4253 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4254 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4255 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4256 |PendingIntent.FLAG_UPDATE_CURRENT);
4257
4258 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4259 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004260 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004261 WeakReference<PendingIntentRecord> ref;
4262 ref = mIntentSenderRecords.get(key);
4263 PendingIntentRecord rec = ref != null ? ref.get() : null;
4264 if (rec != null) {
4265 if (!cancelCurrent) {
4266 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004267 if (rec.key.requestIntent != null) {
4268 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4269 }
4270 if (intents != null) {
4271 intents[intents.length-1] = rec.key.requestIntent;
4272 rec.key.allIntents = intents;
4273 rec.key.allResolvedTypes = resolvedTypes;
4274 } else {
4275 rec.key.allIntents = null;
4276 rec.key.allResolvedTypes = null;
4277 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 return rec;
4280 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004281 rec.canceled = true;
4282 mIntentSenderRecords.remove(key);
4283 }
4284 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 return rec;
4286 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004287 rec = new PendingIntentRecord(this, key, callingUid);
4288 mIntentSenderRecords.put(key, rec.ref);
4289 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4290 if (activity.pendingResults == null) {
4291 activity.pendingResults
4292 = new HashSet<WeakReference<PendingIntentRecord>>();
4293 }
4294 activity.pendingResults.add(rec.ref);
4295 }
4296 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 }
4298
4299 public void cancelIntentSender(IIntentSender sender) {
4300 if (!(sender instanceof PendingIntentRecord)) {
4301 return;
4302 }
4303 synchronized(this) {
4304 PendingIntentRecord rec = (PendingIntentRecord)sender;
4305 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004306 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 .getPackageUid(rec.key.packageName);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004308 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 String msg = "Permission Denial: cancelIntentSender() from pid="
4310 + Binder.getCallingPid()
4311 + ", uid=" + Binder.getCallingUid()
4312 + " is not allowed to cancel packges "
4313 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004314 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 throw new SecurityException(msg);
4316 }
4317 } catch (RemoteException e) {
4318 throw new SecurityException(e);
4319 }
4320 cancelIntentSenderLocked(rec, true);
4321 }
4322 }
4323
4324 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4325 rec.canceled = true;
4326 mIntentSenderRecords.remove(rec.key);
4327 if (cleanActivity && rec.key.activity != null) {
4328 rec.key.activity.pendingResults.remove(rec.ref);
4329 }
4330 }
4331
4332 public String getPackageForIntentSender(IIntentSender pendingResult) {
4333 if (!(pendingResult instanceof PendingIntentRecord)) {
4334 return null;
4335 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004336 try {
4337 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4338 return res.key.packageName;
4339 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341 return null;
4342 }
4343
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004344 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4345 if (!(pendingResult instanceof PendingIntentRecord)) {
4346 return false;
4347 }
4348 try {
4349 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4350 if (res.key.allIntents == null) {
4351 return false;
4352 }
4353 for (int i=0; i<res.key.allIntents.length; i++) {
4354 Intent intent = res.key.allIntents[i];
4355 if (intent.getPackage() != null && intent.getComponent() != null) {
4356 return false;
4357 }
4358 }
4359 return true;
4360 } catch (ClassCastException e) {
4361 }
4362 return false;
4363 }
4364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 public void setProcessLimit(int max) {
4366 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4367 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004368 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004369 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004370 mProcessLimitOverride = max;
4371 }
4372 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 }
4374
4375 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004376 synchronized (this) {
4377 return mProcessLimitOverride;
4378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 }
4380
4381 void foregroundTokenDied(ForegroundToken token) {
4382 synchronized (ActivityManagerService.this) {
4383 synchronized (mPidsSelfLocked) {
4384 ForegroundToken cur
4385 = mForegroundProcesses.get(token.pid);
4386 if (cur != token) {
4387 return;
4388 }
4389 mForegroundProcesses.remove(token.pid);
4390 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4391 if (pr == null) {
4392 return;
4393 }
4394 pr.forcingToForeground = null;
4395 pr.foregroundServices = false;
4396 }
4397 updateOomAdjLocked();
4398 }
4399 }
4400
4401 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4402 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4403 "setProcessForeground()");
4404 synchronized(this) {
4405 boolean changed = false;
4406
4407 synchronized (mPidsSelfLocked) {
4408 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004409 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004410 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 return;
4412 }
4413 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4414 if (oldToken != null) {
4415 oldToken.token.unlinkToDeath(oldToken, 0);
4416 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004417 if (pr != null) {
4418 pr.forcingToForeground = null;
4419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 changed = true;
4421 }
4422 if (isForeground && token != null) {
4423 ForegroundToken newToken = new ForegroundToken() {
4424 public void binderDied() {
4425 foregroundTokenDied(this);
4426 }
4427 };
4428 newToken.pid = pid;
4429 newToken.token = token;
4430 try {
4431 token.linkToDeath(newToken, 0);
4432 mForegroundProcesses.put(pid, newToken);
4433 pr.forcingToForeground = token;
4434 changed = true;
4435 } catch (RemoteException e) {
4436 // If the process died while doing this, we will later
4437 // do the cleanup with the process death link.
4438 }
4439 }
4440 }
4441
4442 if (changed) {
4443 updateOomAdjLocked();
4444 }
4445 }
4446 }
4447
4448 // =========================================================
4449 // PERMISSIONS
4450 // =========================================================
4451
4452 static class PermissionController extends IPermissionController.Stub {
4453 ActivityManagerService mActivityManagerService;
4454 PermissionController(ActivityManagerService activityManagerService) {
4455 mActivityManagerService = activityManagerService;
4456 }
4457
4458 public boolean checkPermission(String permission, int pid, int uid) {
4459 return mActivityManagerService.checkPermission(permission, pid,
4460 uid) == PackageManager.PERMISSION_GRANTED;
4461 }
4462 }
4463
4464 /**
4465 * This can be called with or without the global lock held.
4466 */
4467 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004468 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 // We might be performing an operation on behalf of an indirect binder
4470 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4471 // client identity accordingly before proceeding.
4472 Identity tlsIdentity = sCallerIdentity.get();
4473 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004474 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4476 uid = tlsIdentity.uid;
4477 pid = tlsIdentity.pid;
4478 }
4479
4480 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004481 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 return PackageManager.PERMISSION_GRANTED;
4483 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004484 // Isolated processes don't get any permissions.
4485 if (UserId.isIsolated(uid)) {
4486 return PackageManager.PERMISSION_DENIED;
4487 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004488 // If there is a uid that owns whatever is being accessed, it has
4489 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004490 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004491 return PackageManager.PERMISSION_GRANTED;
4492 }
4493 // If the target is not exported, then nobody else can get to it.
4494 if (!exported) {
4495 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 return PackageManager.PERMISSION_DENIED;
4497 }
4498 if (permission == null) {
4499 return PackageManager.PERMISSION_GRANTED;
4500 }
4501 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004502 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 .checkUidPermission(permission, uid);
4504 } catch (RemoteException e) {
4505 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004506 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 }
4508 return PackageManager.PERMISSION_DENIED;
4509 }
4510
4511 /**
4512 * As the only public entry point for permissions checking, this method
4513 * can enforce the semantic that requesting a check on a null global
4514 * permission is automatically denied. (Internally a null permission
4515 * string is used when calling {@link #checkComponentPermission} in cases
4516 * when only uid-based security is needed.)
4517 *
4518 * This can be called with or without the global lock held.
4519 */
4520 public int checkPermission(String permission, int pid, int uid) {
4521 if (permission == null) {
4522 return PackageManager.PERMISSION_DENIED;
4523 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004524 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526
4527 /**
4528 * Binder IPC calls go through the public entry point.
4529 * This can be called with or without the global lock held.
4530 */
4531 int checkCallingPermission(String permission) {
4532 return checkPermission(permission,
4533 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004534 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 }
4536
4537 /**
4538 * This can be called with or without the global lock held.
4539 */
4540 void enforceCallingPermission(String permission, String func) {
4541 if (checkCallingPermission(permission)
4542 == PackageManager.PERMISSION_GRANTED) {
4543 return;
4544 }
4545
4546 String msg = "Permission Denial: " + func + " from pid="
4547 + Binder.getCallingPid()
4548 + ", uid=" + Binder.getCallingUid()
4549 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004550 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 throw new SecurityException(msg);
4552 }
4553
4554 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004555 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4556 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4557 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4558 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4559 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004561 // Is the component private from the target uid?
4562 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4563
4564 // Acceptable if the there is no read permission needed from the
4565 // target or the target is holding the read permission.
4566 if (!readPerm) {
4567 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004569 == PackageManager.PERMISSION_GRANTED)) {
4570 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 }
4572 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004573
4574 // Acceptable if the there is no write permission needed from the
4575 // target or the target is holding the read permission.
4576 if (!writePerm) {
4577 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004579 == PackageManager.PERMISSION_GRANTED)) {
4580 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581 }
4582 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004583
4584 // Acceptable if there is a path permission matching the URI that
4585 // the target holds the permission on.
4586 PathPermission[] pps = pi.pathPermissions;
4587 if (pps != null && (!readPerm || !writePerm)) {
4588 final String path = uri.getPath();
4589 int i = pps.length;
4590 while (i > 0 && (!readPerm || !writePerm)) {
4591 i--;
4592 PathPermission pp = pps[i];
4593 if (!readPerm) {
4594 final String pprperm = pp.getReadPermission();
4595 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4596 + pprperm + " for " + pp.getPath()
4597 + ": match=" + pp.match(path)
4598 + " check=" + pm.checkUidPermission(pprperm, uid));
4599 if (pprperm != null && pp.match(path) &&
4600 (pm.checkUidPermission(pprperm, uid)
4601 == PackageManager.PERMISSION_GRANTED)) {
4602 readPerm = true;
4603 }
4604 }
4605 if (!writePerm) {
4606 final String ppwperm = pp.getWritePermission();
4607 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4608 + ppwperm + " for " + pp.getPath()
4609 + ": match=" + pp.match(path)
4610 + " check=" + pm.checkUidPermission(ppwperm, uid));
4611 if (ppwperm != null && pp.match(path) &&
4612 (pm.checkUidPermission(ppwperm, uid)
4613 == PackageManager.PERMISSION_GRANTED)) {
4614 writePerm = true;
4615 }
4616 }
4617 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 } catch (RemoteException e) {
4620 return false;
4621 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004622
4623 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 }
4625
4626 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4627 int modeFlags) {
4628 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004629 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 return true;
4631 }
4632 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4633 if (perms == null) return false;
4634 UriPermission perm = perms.get(uri);
4635 if (perm == null) return false;
4636 return (modeFlags&perm.modeFlags) == modeFlags;
4637 }
4638
4639 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004640 enforceNotIsolatedCaller("checkUriPermission");
4641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004642 // Another redirected-binder-call permissions check as in
4643 // {@link checkComponentPermission}.
4644 Identity tlsIdentity = sCallerIdentity.get();
4645 if (tlsIdentity != null) {
4646 uid = tlsIdentity.uid;
4647 pid = tlsIdentity.pid;
4648 }
4649
Amith Yamasani742a6712011-05-04 14:49:28 -07004650 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 // Our own process gets to do everything.
4652 if (pid == MY_PID) {
4653 return PackageManager.PERMISSION_GRANTED;
4654 }
4655 synchronized(this) {
4656 return checkUriPermissionLocked(uri, uid, modeFlags)
4657 ? PackageManager.PERMISSION_GRANTED
4658 : PackageManager.PERMISSION_DENIED;
4659 }
4660 }
4661
Dianne Hackborn39792d22010-08-19 18:01:52 -07004662 /**
4663 * Check if the targetPkg can be granted permission to access uri by
4664 * the callingUid using the given modeFlags. Throws a security exception
4665 * if callingUid is not allowed to do this. Returns the uid of the target
4666 * if the URI permission grant should be performed; returns -1 if it is not
4667 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004668 * If you already know the uid of the target, you can supply it in
4669 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004670 */
4671 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004672 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4674 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4675 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004676 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 }
4678
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004679 if (targetPkg != null) {
4680 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4681 "Checking grant " + targetPkg + " permission to " + uri);
4682 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004683
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004684 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685
4686 // If this is not a content: uri, we can't do anything with it.
4687 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004688 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004689 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004690 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 }
4692
4693 String name = uri.getAuthority();
4694 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004695 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4696 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 if (cpr != null) {
4698 pi = cpr.info;
4699 } else {
4700 try {
4701 pi = pm.resolveContentProvider(name,
4702 PackageManager.GET_URI_PERMISSION_PATTERNS);
4703 } catch (RemoteException ex) {
4704 }
4705 }
4706 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004707 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004708 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 }
4710
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004711 int targetUid = lastTargetUid;
4712 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004713 try {
4714 targetUid = pm.getPackageUid(targetPkg);
4715 if (targetUid < 0) {
4716 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4717 "Can't grant URI permission no uid for: " + targetPkg);
4718 return -1;
4719 }
4720 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004721 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 }
4724
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004725 if (targetUid >= 0) {
4726 // First... does the target actually need this permission?
4727 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4728 // No need to grant the target this permission.
4729 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4730 "Target " + targetPkg + " already has full permission to " + uri);
4731 return -1;
4732 }
4733 } else {
4734 // First... there is no target package, so can anyone access it?
4735 boolean allowed = pi.exported;
4736 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4737 if (pi.readPermission != null) {
4738 allowed = false;
4739 }
4740 }
4741 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4742 if (pi.writePermission != null) {
4743 allowed = false;
4744 }
4745 }
4746 if (allowed) {
4747 return -1;
4748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004749 }
4750
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004751 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004752 if (!pi.grantUriPermissions) {
4753 throw new SecurityException("Provider " + pi.packageName
4754 + "/" + pi.name
4755 + " does not allow granting of Uri permissions (uri "
4756 + uri + ")");
4757 }
4758 if (pi.uriPermissionPatterns != null) {
4759 final int N = pi.uriPermissionPatterns.length;
4760 boolean allowed = false;
4761 for (int i=0; i<N; i++) {
4762 if (pi.uriPermissionPatterns[i] != null
4763 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4764 allowed = true;
4765 break;
4766 }
4767 }
4768 if (!allowed) {
4769 throw new SecurityException("Provider " + pi.packageName
4770 + "/" + pi.name
4771 + " does not allow granting of permission to path of Uri "
4772 + uri);
4773 }
4774 }
4775
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004776 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004778 if (callingUid != Process.myUid()) {
4779 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4780 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4781 throw new SecurityException("Uid " + callingUid
4782 + " does not have permission to uri " + uri);
4783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 }
4785 }
4786
Dianne Hackborn39792d22010-08-19 18:01:52 -07004787 return targetUid;
4788 }
4789
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004790 public int checkGrantUriPermission(int callingUid, String targetPkg,
4791 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004792 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004793 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004794 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004795 }
4796 }
4797
Dianne Hackborn39792d22010-08-19 18:01:52 -07004798 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4799 Uri uri, int modeFlags, UriPermissionOwner owner) {
4800 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4801 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4802 if (modeFlags == 0) {
4803 return;
4804 }
4805
4806 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 // to the uri, and the target doesn't. Let's now give this to
4808 // the target.
4809
Joe Onorato8a9b2202010-02-26 18:56:32 -08004810 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004811 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 HashMap<Uri, UriPermission> targetUris
4814 = mGrantedUriPermissions.get(targetUid);
4815 if (targetUris == null) {
4816 targetUris = new HashMap<Uri, UriPermission>();
4817 mGrantedUriPermissions.put(targetUid, targetUris);
4818 }
4819
4820 UriPermission perm = targetUris.get(uri);
4821 if (perm == null) {
4822 perm = new UriPermission(targetUid, uri);
4823 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004827 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004829 } else {
4830 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4831 perm.readOwners.add(owner);
4832 owner.addReadPermission(perm);
4833 }
4834 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4835 perm.writeOwners.add(owner);
4836 owner.addWritePermission(perm);
4837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 }
4839 }
4840
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004841 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4842 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004843 if (targetPkg == null) {
4844 throw new NullPointerException("targetPkg");
4845 }
4846
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004847 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004848 if (targetUid < 0) {
4849 return;
4850 }
4851
4852 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4853 }
4854
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004855 static class NeededUriGrants extends ArrayList<Uri> {
4856 final String targetPkg;
4857 final int targetUid;
4858 final int flags;
4859
4860 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4861 targetPkg = _targetPkg;
4862 targetUid = _targetUid;
4863 flags = _flags;
4864 }
4865 }
4866
Dianne Hackborn39792d22010-08-19 18:01:52 -07004867 /**
4868 * Like checkGrantUriPermissionLocked, but takes an Intent.
4869 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004870 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4871 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004872 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004873 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4874 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004875 + " from " + intent + "; flags=0x"
4876 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4877
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004878 if (targetPkg == null) {
4879 throw new NullPointerException("targetPkg");
4880 }
4881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004883 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004886 ClipData clip = intent.getClipData();
4887 if (data == null && clip == null) {
4888 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004889 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004890 if (data != null) {
4891 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4892 mode, needed != null ? needed.targetUid : -1);
4893 if (target > 0) {
4894 if (needed == null) {
4895 needed = new NeededUriGrants(targetPkg, target, mode);
4896 }
4897 needed.add(data);
4898 }
4899 }
4900 if (clip != null) {
4901 for (int i=0; i<clip.getItemCount(); i++) {
4902 Uri uri = clip.getItemAt(i).getUri();
4903 if (uri != null) {
4904 int target = -1;
4905 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
4906 mode, needed != null ? needed.targetUid : -1);
4907 if (target > 0) {
4908 if (needed == null) {
4909 needed = new NeededUriGrants(targetPkg, target, mode);
4910 }
4911 needed.add(uri);
4912 }
4913 } else {
4914 Intent clipIntent = clip.getItemAt(i).getIntent();
4915 if (clipIntent != null) {
4916 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
4917 callingUid, targetPkg, clipIntent, mode, needed);
4918 if (newNeeded != null) {
4919 needed = newNeeded;
4920 }
4921 }
4922 }
4923 }
4924 }
4925
4926 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004927 }
4928
4929 /**
4930 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4931 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004932 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
4933 UriPermissionOwner owner) {
4934 if (needed != null) {
4935 for (int i=0; i<needed.size(); i++) {
4936 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
4937 needed.get(i), needed.flags, owner);
4938 }
4939 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004940 }
4941
4942 void grantUriPermissionFromIntentLocked(int callingUid,
4943 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004944 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08004945 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004946 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004947 return;
4948 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004949
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004950 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 }
4952
4953 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4954 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004955 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 synchronized(this) {
4957 final ProcessRecord r = getRecordForAppLocked(caller);
4958 if (r == null) {
4959 throw new SecurityException("Unable to find app for caller "
4960 + caller
4961 + " when granting permission to uri " + uri);
4962 }
4963 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004964 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 }
4966 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004967 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004968 }
4969
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004970 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 null);
4972 }
4973 }
4974
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004975 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4977 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4978 HashMap<Uri, UriPermission> perms
4979 = mGrantedUriPermissions.get(perm.uid);
4980 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004981 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004982 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 perms.remove(perm.uri);
4984 if (perms.size() == 0) {
4985 mGrantedUriPermissions.remove(perm.uid);
4986 }
4987 }
4988 }
4989 }
4990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004991 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4992 int modeFlags) {
4993 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4994 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4995 if (modeFlags == 0) {
4996 return;
4997 }
4998
Joe Onorato8a9b2202010-02-26 18:56:32 -08004999 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005000 "Revoking all granted permissions to " + uri);
5001
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005002 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005003
5004 final String authority = uri.getAuthority();
5005 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005006 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5007 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005008 if (cpr != null) {
5009 pi = cpr.info;
5010 } else {
5011 try {
5012 pi = pm.resolveContentProvider(authority,
5013 PackageManager.GET_URI_PERMISSION_PATTERNS);
5014 } catch (RemoteException ex) {
5015 }
5016 }
5017 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005018 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 return;
5020 }
5021
5022 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005023 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 // Right now, if you are not the original owner of the permission,
5025 // you are not allowed to revoke it.
5026 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5027 throw new SecurityException("Uid " + callingUid
5028 + " does not have permission to uri " + uri);
5029 //}
5030 }
5031
5032 // Go through all of the permissions and remove any that match.
5033 final List<String> SEGMENTS = uri.getPathSegments();
5034 if (SEGMENTS != null) {
5035 final int NS = SEGMENTS.size();
5036 int N = mGrantedUriPermissions.size();
5037 for (int i=0; i<N; i++) {
5038 HashMap<Uri, UriPermission> perms
5039 = mGrantedUriPermissions.valueAt(i);
5040 Iterator<UriPermission> it = perms.values().iterator();
5041 toploop:
5042 while (it.hasNext()) {
5043 UriPermission perm = it.next();
5044 Uri targetUri = perm.uri;
5045 if (!authority.equals(targetUri.getAuthority())) {
5046 continue;
5047 }
5048 List<String> targetSegments = targetUri.getPathSegments();
5049 if (targetSegments == null) {
5050 continue;
5051 }
5052 if (targetSegments.size() < NS) {
5053 continue;
5054 }
5055 for (int j=0; j<NS; j++) {
5056 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5057 continue toploop;
5058 }
5059 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005060 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005061 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 perm.clearModes(modeFlags);
5063 if (perm.modeFlags == 0) {
5064 it.remove();
5065 }
5066 }
5067 if (perms.size() == 0) {
5068 mGrantedUriPermissions.remove(
5069 mGrantedUriPermissions.keyAt(i));
5070 N--;
5071 i--;
5072 }
5073 }
5074 }
5075 }
5076
5077 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5078 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005079 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 synchronized(this) {
5081 final ProcessRecord r = getRecordForAppLocked(caller);
5082 if (r == null) {
5083 throw new SecurityException("Unable to find app for caller "
5084 + caller
5085 + " when revoking permission to uri " + uri);
5086 }
5087 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005088 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 return;
5090 }
5091
5092 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5093 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5094 if (modeFlags == 0) {
5095 return;
5096 }
5097
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005098 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099
5100 final String authority = uri.getAuthority();
5101 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005102 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103 if (cpr != null) {
5104 pi = cpr.info;
5105 } else {
5106 try {
5107 pi = pm.resolveContentProvider(authority,
5108 PackageManager.GET_URI_PERMISSION_PATTERNS);
5109 } catch (RemoteException ex) {
5110 }
5111 }
5112 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005113 Slog.w(TAG, "No content provider found for permission revoke: "
5114 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 return;
5116 }
5117
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005118 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 }
5120 }
5121
Dianne Hackborn7e269642010-08-25 19:50:20 -07005122 @Override
5123 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005124 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005125 synchronized(this) {
5126 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5127 return owner.getExternalTokenLocked();
5128 }
5129 }
5130
5131 @Override
5132 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5133 Uri uri, int modeFlags) {
5134 synchronized(this) {
5135 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5136 if (owner == null) {
5137 throw new IllegalArgumentException("Unknown owner: " + token);
5138 }
5139 if (fromUid != Binder.getCallingUid()) {
5140 if (Binder.getCallingUid() != Process.myUid()) {
5141 // Only system code can grant URI permissions on behalf
5142 // of other users.
5143 throw new SecurityException("nice try");
5144 }
5145 }
5146 if (targetPkg == null) {
5147 throw new IllegalArgumentException("null target");
5148 }
5149 if (uri == null) {
5150 throw new IllegalArgumentException("null uri");
5151 }
5152
5153 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5154 }
5155 }
5156
5157 @Override
5158 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5159 synchronized(this) {
5160 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5161 if (owner == null) {
5162 throw new IllegalArgumentException("Unknown owner: " + token);
5163 }
5164
5165 if (uri == null) {
5166 owner.removeUriPermissionsLocked(mode);
5167 } else {
5168 owner.removeUriPermissionLocked(uri, mode);
5169 }
5170 }
5171 }
5172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5174 synchronized (this) {
5175 ProcessRecord app =
5176 who != null ? getRecordForAppLocked(who) : null;
5177 if (app == null) return;
5178
5179 Message msg = Message.obtain();
5180 msg.what = WAIT_FOR_DEBUGGER_MSG;
5181 msg.obj = app;
5182 msg.arg1 = waiting ? 1 : 0;
5183 mHandler.sendMessage(msg);
5184 }
5185 }
5186
5187 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005188 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5189 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005190 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005191 outInfo.threshold = homeAppMem;
5192 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5193 outInfo.hiddenAppThreshold = hiddenAppMem;
5194 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005195 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005196 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5197 ProcessList.VISIBLE_APP_ADJ);
5198 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5199 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 }
5201
5202 // =========================================================
5203 // TASK MANAGEMENT
5204 // =========================================================
5205
5206 public List getTasks(int maxNum, int flags,
5207 IThumbnailReceiver receiver) {
5208 ArrayList list = new ArrayList();
5209
5210 PendingThumbnailsRecord pending = null;
5211 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005212 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213
5214 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005215 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5217 + ", receiver=" + receiver);
5218
5219 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5220 != PackageManager.PERMISSION_GRANTED) {
5221 if (receiver != null) {
5222 // If the caller wants to wait for pending thumbnails,
5223 // it ain't gonna get them.
5224 try {
5225 receiver.finished();
5226 } catch (RemoteException ex) {
5227 }
5228 }
5229 String msg = "Permission Denial: getTasks() from pid="
5230 + Binder.getCallingPid()
5231 + ", uid=" + Binder.getCallingUid()
5232 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005233 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 throw new SecurityException(msg);
5235 }
5236
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005237 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005238 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005239 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005240 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 TaskRecord curTask = null;
5242 int numActivities = 0;
5243 int numRunning = 0;
5244 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005245 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005247 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248
5249 // Initialize state for next task if needed.
5250 if (top == null ||
5251 (top.state == ActivityState.INITIALIZING
5252 && top.task == r.task)) {
5253 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 curTask = r.task;
5255 numActivities = numRunning = 0;
5256 }
5257
5258 // Add 'r' into the current task.
5259 numActivities++;
5260 if (r.app != null && r.app.thread != null) {
5261 numRunning++;
5262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263
Joe Onorato8a9b2202010-02-26 18:56:32 -08005264 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005265 TAG, r.intent.getComponent().flattenToShortString()
5266 + ": task=" + r.task);
5267
5268 // If the next one is a different task, generate a new
5269 // TaskInfo entry for what we have.
5270 if (next == null || next.task != curTask) {
5271 ActivityManager.RunningTaskInfo ci
5272 = new ActivityManager.RunningTaskInfo();
5273 ci.id = curTask.taskId;
5274 ci.baseActivity = r.intent.getComponent();
5275 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005276 if (top.thumbHolder != null) {
5277 ci.description = top.thumbHolder.lastDescription;
5278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 ci.numActivities = numActivities;
5280 ci.numRunning = numRunning;
5281 //System.out.println(
5282 // "#" + maxNum + ": " + " descr=" + ci.description);
5283 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005284 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005285 TAG, "State=" + top.state + "Idle=" + top.idle
5286 + " app=" + top.app
5287 + " thr=" + (top.app != null ? top.app.thread : null));
5288 if (top.state == ActivityState.RESUMED
5289 || top.state == ActivityState.PAUSING) {
5290 if (top.idle && top.app != null
5291 && top.app.thread != null) {
5292 topRecord = top;
5293 topThumbnail = top.app.thread;
5294 } else {
5295 top.thumbnailNeeded = true;
5296 }
5297 }
5298 if (pending == null) {
5299 pending = new PendingThumbnailsRecord(receiver);
5300 }
5301 pending.pendingRecords.add(top);
5302 }
5303 list.add(ci);
5304 maxNum--;
5305 top = null;
5306 }
5307 }
5308
5309 if (pending != null) {
5310 mPendingThumbnails.add(pending);
5311 }
5312 }
5313
Joe Onorato8a9b2202010-02-26 18:56:32 -08005314 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315
5316 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005317 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005319 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005321 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005322 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 }
5324 }
5325
5326 if (pending == null && receiver != null) {
5327 // In this case all thumbnails were available and the client
5328 // is being asked to be told when the remaining ones come in...
5329 // which is unusually, since the top-most currently running
5330 // activity should never have a canned thumbnail! Oh well.
5331 try {
5332 receiver.finished();
5333 } catch (RemoteException ex) {
5334 }
5335 }
5336
5337 return list;
5338 }
5339
5340 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5341 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005342 final int callingUid = Binder.getCallingUid();
5343 // If it's the system uid asking, then use the current user id.
5344 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5345 // require the entire list.
5346 final int callingUserId = callingUid == Process.SYSTEM_UID
5347 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 synchronized (this) {
5349 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5350 "getRecentTasks()");
5351
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005352 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 final int N = mRecentTasks.size();
5355 ArrayList<ActivityManager.RecentTaskInfo> res
5356 = new ArrayList<ActivityManager.RecentTaskInfo>(
5357 maxNum < N ? maxNum : N);
5358 for (int i=0; i<N && maxNum > 0; i++) {
5359 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005360 // Only add calling user's recent tasks
5361 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005362 // Return the entry if desired by the caller. We always return
5363 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005364 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005365 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5366 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005367
Dianne Hackborn905577f2011-09-07 18:31:28 -07005368 if (i == 0
5369 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 || (tr.intent == null)
5371 || ((tr.intent.getFlags()
5372 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5373 ActivityManager.RecentTaskInfo rti
5374 = new ActivityManager.RecentTaskInfo();
5375 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005376 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 rti.baseIntent = new Intent(
5378 tr.intent != null ? tr.intent : tr.affinityIntent);
5379 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005380 rti.description = tr.lastDescription;
5381
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005382 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5383 // Check whether this activity is currently available.
5384 try {
5385 if (rti.origActivity != null) {
5386 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5387 continue;
5388 }
5389 } else if (rti.baseIntent != null) {
5390 if (pm.queryIntentActivities(rti.baseIntent,
5391 null, 0) == null) {
5392 continue;
5393 }
5394 }
5395 } catch (RemoteException e) {
5396 // Will never happen.
5397 }
5398 }
5399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 res.add(rti);
5401 maxNum--;
5402 }
5403 }
5404 return res;
5405 }
5406 }
5407
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005408 private TaskRecord taskForIdLocked(int id) {
5409 final int N = mRecentTasks.size();
5410 for (int i=0; i<N; i++) {
5411 TaskRecord tr = mRecentTasks.get(i);
5412 if (tr.taskId == id) {
5413 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005414 }
5415 }
5416 return null;
5417 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005418
5419 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5420 synchronized (this) {
5421 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5422 "getTaskThumbnails()");
5423 TaskRecord tr = taskForIdLocked(id);
5424 if (tr != null) {
5425 return mMainStack.getTaskThumbnailsLocked(tr);
5426 }
5427 }
5428 return null;
5429 }
5430
5431 public boolean removeSubTask(int taskId, int subTaskIndex) {
5432 synchronized (this) {
5433 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5434 "removeSubTask()");
5435 long ident = Binder.clearCallingIdentity();
5436 try {
5437 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5438 } finally {
5439 Binder.restoreCallingIdentity(ident);
5440 }
5441 }
5442 }
5443
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005444 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005445 TaskRecord tr = root.task;
5446 Intent baseIntent = new Intent(
5447 tr.intent != null ? tr.intent : tr.affinityIntent);
5448 ComponentName component = baseIntent.getComponent();
5449 if (component == null) {
5450 Slog.w(TAG, "Now component for base intent of task: " + tr);
5451 return;
5452 }
5453
5454 // Find any running services associated with this app.
5455 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005456 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005457 if (sr.packageName.equals(component.getPackageName())) {
5458 services.add(sr);
5459 }
5460 }
5461
5462 // Take care of any running services associated with the app.
5463 for (int i=0; i<services.size(); i++) {
5464 ServiceRecord sr = services.get(i);
5465 if (sr.startRequested) {
5466 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005467 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005468 stopServiceLocked(sr);
5469 } else {
5470 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005471 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005472 if (sr.app != null && sr.app.thread != null) {
5473 sendServiceArgsLocked(sr, false);
5474 }
5475 }
5476 }
5477 }
5478
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005479 if (killProcesses) {
5480 // Find any running processes associated with this app.
5481 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5482 SparseArray<ProcessRecord> appProcs
5483 = mProcessNames.getMap().get(component.getPackageName());
5484 if (appProcs != null) {
5485 for (int i=0; i<appProcs.size(); i++) {
5486 procs.add(appProcs.valueAt(i));
5487 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005488 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005489
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005490 // Kill the running processes.
5491 for (int i=0; i<procs.size(); i++) {
5492 ProcessRecord pr = procs.get(i);
5493 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5494 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5495 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5496 pr.processName, pr.setAdj, "remove task");
5497 Process.killProcessQuiet(pr.pid);
5498 } else {
5499 pr.waitingToKill = "remove task";
5500 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005501 }
5502 }
5503 }
5504
5505 public boolean removeTask(int taskId, int flags) {
5506 synchronized (this) {
5507 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5508 "removeTask()");
5509 long ident = Binder.clearCallingIdentity();
5510 try {
5511 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5512 if (r != null) {
5513 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005514 cleanUpRemovedTaskLocked(r,
5515 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005516 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005517 } else {
5518 TaskRecord tr = null;
5519 int i=0;
5520 while (i < mRecentTasks.size()) {
5521 TaskRecord t = mRecentTasks.get(i);
5522 if (t.taskId == taskId) {
5523 tr = t;
5524 break;
5525 }
5526 i++;
5527 }
5528 if (tr != null) {
5529 if (tr.numActivities <= 0) {
5530 // Caller is just removing a recent task that is
5531 // not actively running. That is easy!
5532 mRecentTasks.remove(i);
5533 } else {
5534 Slog.w(TAG, "removeTask: task " + taskId
5535 + " does not have activities to remove, "
5536 + " but numActivities=" + tr.numActivities
5537 + ": " + tr);
5538 }
5539 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005540 }
5541 } finally {
5542 Binder.restoreCallingIdentity(ident);
5543 }
5544 }
5545 return false;
5546 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5549 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005550 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 TaskRecord jt = startTask;
5552
5553 // First look backwards
5554 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005555 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 if (r.task != jt) {
5557 jt = r.task;
5558 if (affinity.equals(jt.affinity)) {
5559 return j;
5560 }
5561 }
5562 }
5563
5564 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005565 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 jt = startTask;
5567 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005568 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 if (r.task != jt) {
5570 if (affinity.equals(jt.affinity)) {
5571 return j;
5572 }
5573 jt = r.task;
5574 }
5575 }
5576
5577 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005578 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 return N-1;
5580 }
5581
5582 return -1;
5583 }
5584
5585 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005586 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005588 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5590 "moveTaskToFront()");
5591
5592 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005593 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5594 Binder.getCallingUid(), "Task to front")) {
5595 return;
5596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 final long origId = Binder.clearCallingIdentity();
5598 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005599 TaskRecord tr = taskForIdLocked(task);
5600 if (tr != null) {
5601 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5602 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005604 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5605 // Caller wants the home activity moved with it. To accomplish this,
5606 // we'll just move the home task to the top first.
5607 mMainStack.moveHomeToFrontLocked();
5608 }
5609 mMainStack.moveTaskToFrontLocked(tr, null);
5610 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005612 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5613 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005615 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5616 mMainStack.mUserLeaving = true;
5617 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005618 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5619 // Caller wants the home activity moved with it. To accomplish this,
5620 // we'll just move the home task to the top first.
5621 mMainStack.moveHomeToFrontLocked();
5622 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005623 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 return;
5625 }
5626 }
5627 } finally {
5628 Binder.restoreCallingIdentity(origId);
5629 }
5630 }
5631 }
5632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 public void moveTaskToBack(int task) {
5634 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5635 "moveTaskToBack()");
5636
5637 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005638 if (mMainStack.mResumedActivity != null
5639 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005640 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5641 Binder.getCallingUid(), "Task to back")) {
5642 return;
5643 }
5644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005646 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 Binder.restoreCallingIdentity(origId);
5648 }
5649 }
5650
5651 /**
5652 * Moves an activity, and all of the other activities within the same task, to the bottom
5653 * of the history stack. The activity's order within the task is unchanged.
5654 *
5655 * @param token A reference to the activity we wish to move
5656 * @param nonRoot If false then this only works if the activity is the root
5657 * of a task; if true it will work for any activity in a task.
5658 * @return Returns true if the move completed, false if not.
5659 */
5660 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005661 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 synchronized(this) {
5663 final long origId = Binder.clearCallingIdentity();
5664 int taskId = getTaskForActivityLocked(token, !nonRoot);
5665 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005666 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 }
5668 Binder.restoreCallingIdentity(origId);
5669 }
5670 return false;
5671 }
5672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 public void moveTaskBackwards(int task) {
5674 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5675 "moveTaskBackwards()");
5676
5677 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005678 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5679 Binder.getCallingUid(), "Task backwards")) {
5680 return;
5681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 final long origId = Binder.clearCallingIdentity();
5683 moveTaskBackwardsLocked(task);
5684 Binder.restoreCallingIdentity(origId);
5685 }
5686 }
5687
5688 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005689 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 }
5691
5692 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5693 synchronized(this) {
5694 return getTaskForActivityLocked(token, onlyRoot);
5695 }
5696 }
5697
5698 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005699 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 TaskRecord lastTask = null;
5701 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005702 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005703 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 if (!onlyRoot || lastTask != r.task) {
5705 return r.task.taskId;
5706 }
5707 return -1;
5708 }
5709 lastTask = r.task;
5710 }
5711
5712 return -1;
5713 }
5714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 // =========================================================
5716 // THUMBNAILS
5717 // =========================================================
5718
5719 public void reportThumbnail(IBinder token,
5720 Bitmap thumbnail, CharSequence description) {
5721 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5722 final long origId = Binder.clearCallingIdentity();
5723 sendPendingThumbnail(null, token, thumbnail, description, true);
5724 Binder.restoreCallingIdentity(origId);
5725 }
5726
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005727 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 Bitmap thumbnail, CharSequence description, boolean always) {
5729 TaskRecord task = null;
5730 ArrayList receivers = null;
5731
5732 //System.out.println("Send pending thumbnail: " + r);
5733
5734 synchronized(this) {
5735 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005736 r = mMainStack.isInStackLocked(token);
5737 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 return;
5739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005741 if (thumbnail == null && r.thumbHolder != null) {
5742 thumbnail = r.thumbHolder.lastThumbnail;
5743 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 }
5745 if (thumbnail == null && !always) {
5746 // If there is no thumbnail, and this entry is not actually
5747 // going away, then abort for now and pick up the next
5748 // thumbnail we get.
5749 return;
5750 }
5751 task = r.task;
5752
5753 int N = mPendingThumbnails.size();
5754 int i=0;
5755 while (i<N) {
5756 PendingThumbnailsRecord pr =
5757 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5758 //System.out.println("Looking in " + pr.pendingRecords);
5759 if (pr.pendingRecords.remove(r)) {
5760 if (receivers == null) {
5761 receivers = new ArrayList();
5762 }
5763 receivers.add(pr);
5764 if (pr.pendingRecords.size() == 0) {
5765 pr.finished = true;
5766 mPendingThumbnails.remove(i);
5767 N--;
5768 continue;
5769 }
5770 }
5771 i++;
5772 }
5773 }
5774
5775 if (receivers != null) {
5776 final int N = receivers.size();
5777 for (int i=0; i<N; i++) {
5778 try {
5779 PendingThumbnailsRecord pr =
5780 (PendingThumbnailsRecord)receivers.get(i);
5781 pr.receiver.newThumbnail(
5782 task != null ? task.taskId : -1, thumbnail, description);
5783 if (pr.finished) {
5784 pr.receiver.finished();
5785 }
5786 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005787 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 }
5789 }
5790 }
5791 }
5792
5793 // =========================================================
5794 // CONTENT PROVIDERS
5795 // =========================================================
5796
Jeff Brown10e89712011-07-08 18:52:57 -07005797 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5798 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005800 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005801 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005802 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 } catch (RemoteException ex) {
5804 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005805 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005806 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5807 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 if (providers != null) {
5809 final int N = providers.size();
5810 for (int i=0; i<N; i++) {
5811 ProviderInfo cpi =
5812 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005813
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005814 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005815 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005817 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005818 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005820 if (DEBUG_MU)
5821 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 app.pubProviders.put(cpi.name, cpr);
5823 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005824 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 }
5826 }
5827 return providers;
5828 }
5829
5830 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005831 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005833 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005835 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005836 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 return null;
5838 }
5839 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005840 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 == PackageManager.PERMISSION_GRANTED) {
5842 return null;
5843 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005844
5845 PathPermission[] pps = cpi.pathPermissions;
5846 if (pps != null) {
5847 int i = pps.length;
5848 while (i > 0) {
5849 i--;
5850 PathPermission pp = pps[i];
5851 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005852 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005853 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005854 return null;
5855 }
5856 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005857 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005858 == PackageManager.PERMISSION_GRANTED) {
5859 return null;
5860 }
5861 }
5862 }
5863
Dianne Hackbornb424b632010-08-18 15:59:05 -07005864 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5865 if (perms != null) {
5866 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5867 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5868 return null;
5869 }
5870 }
5871 }
5872
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005873 String msg;
5874 if (!cpi.exported) {
5875 msg = "Permission Denial: opening provider " + cpi.name
5876 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5877 + ", uid=" + callingUid + ") that is not exported from uid "
5878 + cpi.applicationInfo.uid;
5879 } else {
5880 msg = "Permission Denial: opening provider " + cpi.name
5881 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5882 + ", uid=" + callingUid + ") requires "
5883 + cpi.readPermission + " or " + cpi.writePermission;
5884 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005885 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886 return msg;
5887 }
5888
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005889 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5890 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005891 if (r != null) {
5892 Integer cnt = r.conProviders.get(cpr);
5893 if (DEBUG_PROVIDER) Slog.v(TAG,
5894 "Adding provider requested by "
5895 + r.processName + " from process "
5896 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5897 + " cnt=" + (cnt == null ? 1 : cnt));
5898 if (cnt == null) {
5899 cpr.clients.add(r);
5900 r.conProviders.put(cpr, new Integer(1));
5901 return true;
5902 } else {
5903 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5904 }
5905 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005906 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005907 }
5908 return false;
5909 }
5910
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005911 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5912 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005913 if (r != null) {
5914 Integer cnt = r.conProviders.get(cpr);
5915 if (DEBUG_PROVIDER) Slog.v(TAG,
5916 "Removing provider requested by "
5917 + r.processName + " from process "
5918 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5919 + " cnt=" + cnt);
5920 if (cnt == null || cnt.intValue() <= 1) {
5921 cpr.clients.remove(r);
5922 r.conProviders.remove(cpr);
5923 return true;
5924 } else {
5925 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5926 }
5927 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005928 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005929 }
5930 return false;
5931 }
5932
Amith Yamasani742a6712011-05-04 14:49:28 -07005933 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005934 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 ContentProviderRecord cpr;
5936 ProviderInfo cpi = null;
5937
5938 synchronized(this) {
5939 ProcessRecord r = null;
5940 if (caller != null) {
5941 r = getRecordForAppLocked(caller);
5942 if (r == null) {
5943 throw new SecurityException(
5944 "Unable to find app for caller " + caller
5945 + " (pid=" + Binder.getCallingPid()
5946 + ") when getting content provider " + name);
5947 }
5948 }
5949
5950 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005951 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005952 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005953 boolean providerRunning = cpr != null;
5954 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005956 String msg;
5957 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5958 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 }
5960
5961 if (r != null && cpr.canRunHere(r)) {
5962 // This provider has been published or is in the process
5963 // of being published... but it is also allowed to run
5964 // in the caller's process, so don't make a connection
5965 // and just let the caller instantiate its own instance.
5966 if (cpr.provider != null) {
5967 // don't give caller the provider object, it needs
5968 // to make its own.
5969 cpr = new ContentProviderRecord(cpr);
5970 }
5971 return cpr;
5972 }
5973
5974 final long origId = Binder.clearCallingIdentity();
5975
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005976 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005978 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005979 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005980 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005981 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005982 // make sure to count it as being accessed and thus
5983 // back up on the LRU list. This is good because
5984 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005985 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07005986 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005987 }
5988
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005989 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005990 if (false) {
5991 if (cpr.name.flattenToShortString().equals(
5992 "com.android.providers.calendar/.CalendarProvider2")) {
5993 Slog.v(TAG, "****************** KILLING "
5994 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005995 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005996 }
5997 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005998 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005999 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6000 // NOTE: there is still a race here where a signal could be
6001 // pending on the process even though we managed to update its
6002 // adj level. Not sure what to do about this, but at least
6003 // the race is now smaller.
6004 if (!success) {
6005 // Uh oh... it looks like the provider's process
6006 // has been killed on us. We need to wait for a new
6007 // process to be started, and make sure its death
6008 // doesn't kill our process.
6009 Slog.i(TAG,
6010 "Existing provider " + cpr.name.flattenToShortString()
6011 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006012 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006013 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006014 if (!lastRef) {
6015 // This wasn't the last ref our process had on
6016 // the provider... we have now been killed, bail.
6017 return null;
6018 }
6019 providerRunning = false;
6020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 }
6022
6023 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006026 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006028 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006029 resolveContentProvider(name,
6030 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 } catch (RemoteException ex) {
6032 }
6033 if (cpi == null) {
6034 return null;
6035 }
6036
Amith Yamasani742a6712011-05-04 14:49:28 -07006037 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6038 Binder.getOrigCallingUser());
6039
Dianne Hackbornb424b632010-08-18 15:59:05 -07006040 String msg;
6041 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6042 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 }
6044
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006045 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006046 && !cpi.processName.equals("system")) {
6047 // If this content provider does not run in the system
6048 // process, and the system is not yet ready to run other
6049 // processes, then fail fast instead of hanging.
6050 throw new IllegalArgumentException(
6051 "Attempt to launch content provider before system ready");
6052 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006053
6054 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006055 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 final boolean firstClass = cpr == null;
6057 if (firstClass) {
6058 try {
6059 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006060 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 getApplicationInfo(
6062 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006063 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006065 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 + cpi.name);
6067 return null;
6068 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006069 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006070 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 } catch (RemoteException ex) {
6072 // pm is in same process, this will never happen.
6073 }
6074 }
6075
6076 if (r != null && cpr.canRunHere(r)) {
6077 // If this is a multiprocess provider, then just return its
6078 // info and allow the caller to instantiate it. Only do
6079 // this if the provider is the same user as the caller's
6080 // process, or can run as root (so can be in any process).
6081 return cpr;
6082 }
6083
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006084 if (DEBUG_PROVIDER) {
6085 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006086 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006087 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
6089
6090 // This is single process, and our app is now connecting to it.
6091 // See if we are already in the process of launching this
6092 // provider.
6093 final int N = mLaunchingProviders.size();
6094 int i;
6095 for (i=0; i<N; i++) {
6096 if (mLaunchingProviders.get(i) == cpr) {
6097 break;
6098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 }
6100
6101 // If the provider is not already being launched, then get it
6102 // started.
6103 if (i >= N) {
6104 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006105
6106 try {
6107 // Content provider is now in use, its package can't be stopped.
6108 try {
6109 AppGlobals.getPackageManager().setPackageStoppedState(
6110 cpr.appInfo.packageName, false);
6111 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006112 } catch (IllegalArgumentException e) {
6113 Slog.w(TAG, "Failed trying to unstop package "
6114 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006115 }
6116
6117 ProcessRecord proc = startProcessLocked(cpi.processName,
6118 cpr.appInfo, false, 0, "content provider",
6119 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006120 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006121 if (proc == null) {
6122 Slog.w(TAG, "Unable to launch app "
6123 + cpi.applicationInfo.packageName + "/"
6124 + cpi.applicationInfo.uid + " for provider "
6125 + name + ": process is bad");
6126 return null;
6127 }
6128 cpr.launchingApp = proc;
6129 mLaunchingProviders.add(cpr);
6130 } finally {
6131 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 }
6134
6135 // Make sure the provider is published (the same provider class
6136 // may be published under multiple names).
6137 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006138 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006140
Amith Yamasani742a6712011-05-04 14:49:28 -07006141 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006142 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 }
6144 }
6145
6146 // Wait for the provider to be published...
6147 synchronized (cpr) {
6148 while (cpr.provider == null) {
6149 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006150 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 + cpi.applicationInfo.packageName + "/"
6152 + cpi.applicationInfo.uid + " for provider "
6153 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006154 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 cpi.applicationInfo.packageName,
6156 cpi.applicationInfo.uid, name);
6157 return null;
6158 }
6159 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006160 if (DEBUG_MU) {
6161 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6162 + cpr.launchingApp);
6163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 cpr.wait();
6165 } catch (InterruptedException ex) {
6166 }
6167 }
6168 }
6169 return cpr;
6170 }
6171
6172 public final ContentProviderHolder getContentProvider(
6173 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006174 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 if (caller == null) {
6176 String msg = "null IApplicationThread when getting content provider "
6177 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006178 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 throw new SecurityException(msg);
6180 }
6181
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006182 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 }
6184
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006185 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6186 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6187 "Do not have permission in call getContentProviderExternal()");
6188 return getContentProviderExternalUnchecked(name, token);
6189 }
6190
6191 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6192 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 }
6194
6195 /**
6196 * Drop a content provider from a ProcessRecord's bookkeeping
6197 * @param cpr
6198 */
6199 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006200 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006202 int userId = UserId.getUserId(Binder.getCallingUid());
6203 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006205 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006206 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006207 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 return;
6209 }
6210 final ProcessRecord r = getRecordForAppLocked(caller);
6211 if (r == null) {
6212 throw new SecurityException(
6213 "Unable to find app for caller " + caller +
6214 " when removing content provider " + name);
6215 }
6216 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006217 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006218 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6219 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6220 + r.info.processName + " from process "
6221 + localCpr.appInfo.processName);
6222 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006224 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006225 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 return;
6227 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006228 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006229 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 }
6233 }
6234
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006235 public void removeContentProviderExternal(String name, IBinder token) {
6236 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6237 "Do not have permission in call removeContentProviderExternal()");
6238 removeContentProviderExternalUnchecked(name, token);
6239 }
6240
6241 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006243 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6244 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 if(cpr == null) {
6246 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006247 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 return;
6249 }
6250
6251 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006252 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006253 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6254 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006255 if (localCpr.hasExternalProcessHandles()) {
6256 if (localCpr.removeExternalProcessHandleLocked(token)) {
6257 updateOomAdjLocked();
6258 } else {
6259 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6260 + " with no external reference for token: "
6261 + token + ".");
6262 }
6263 } else {
6264 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6265 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 }
6268 }
6269
6270 public final void publishContentProviders(IApplicationThread caller,
6271 List<ContentProviderHolder> providers) {
6272 if (providers == null) {
6273 return;
6274 }
6275
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006276 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 synchronized(this) {
6278 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006279 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006280 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 if (r == null) {
6282 throw new SecurityException(
6283 "Unable to find app for caller " + caller
6284 + " (pid=" + Binder.getCallingPid()
6285 + ") when publishing content providers");
6286 }
6287
6288 final long origId = Binder.clearCallingIdentity();
6289
6290 final int N = providers.size();
6291 for (int i=0; i<N; i++) {
6292 ContentProviderHolder src = providers.get(i);
6293 if (src == null || src.info == null || src.provider == null) {
6294 continue;
6295 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006296 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006297 if (DEBUG_MU)
6298 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006300 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006301 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 String names[] = dst.info.authority.split(";");
6303 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006304 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 }
6306
6307 int NL = mLaunchingProviders.size();
6308 int j;
6309 for (j=0; j<NL; j++) {
6310 if (mLaunchingProviders.get(j) == dst) {
6311 mLaunchingProviders.remove(j);
6312 j--;
6313 NL--;
6314 }
6315 }
6316 synchronized (dst) {
6317 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006318 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 dst.notifyAll();
6320 }
6321 updateOomAdjLocked(r);
6322 }
6323 }
6324
6325 Binder.restoreCallingIdentity(origId);
6326 }
6327 }
6328
6329 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006330 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006331 synchronized (mSelf) {
6332 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6333 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006334 if (providers != null) {
6335 for (int i=providers.size()-1; i>=0; i--) {
6336 ProviderInfo pi = (ProviderInfo)providers.get(i);
6337 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6338 Slog.w(TAG, "Not installing system proc provider " + pi.name
6339 + ": not system .apk");
6340 providers.remove(i);
6341 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006342 }
6343 }
6344 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006345 if (providers != null) {
6346 mSystemThread.installSystemProviders(providers);
6347 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006348
6349 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006350
6351 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 }
6353
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006354 /**
6355 * Allows app to retrieve the MIME type of a URI without having permission
6356 * to access its content provider.
6357 *
6358 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6359 *
6360 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6361 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6362 */
6363 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006364 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006365 final String name = uri.getAuthority();
6366 final long ident = Binder.clearCallingIdentity();
6367 ContentProviderHolder holder = null;
6368
6369 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006370 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006371 if (holder != null) {
6372 return holder.provider.getType(uri);
6373 }
6374 } catch (RemoteException e) {
6375 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6376 return null;
6377 } finally {
6378 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006379 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006380 }
6381 Binder.restoreCallingIdentity(ident);
6382 }
6383
6384 return null;
6385 }
6386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 // =========================================================
6388 // GLOBAL MANAGEMENT
6389 // =========================================================
6390
6391 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006392 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 String proc = customProcess != null ? customProcess : info.processName;
6394 BatteryStatsImpl.Uid.Proc ps = null;
6395 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006396 int uid = info.uid;
6397 if (isolated) {
6398 int userId = UserId.getUserId(uid);
6399 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6400 uid = 0;
6401 while (true) {
6402 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6403 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6404 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6405 }
6406 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6407 mNextIsolatedProcessUid++;
6408 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6409 // No process for this uid, use it.
6410 break;
6411 }
6412 stepsLeft--;
6413 if (stepsLeft <= 0) {
6414 return null;
6415 }
6416 }
6417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 synchronized (stats) {
6419 ps = stats.getProcessStatsLocked(info.uid, proc);
6420 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006421 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006424 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6425 ProcessRecord app;
6426 if (!isolated) {
6427 app = getProcessRecordLocked(info.processName, info.uid);
6428 } else {
6429 app = null;
6430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431
6432 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006433 app = newProcessRecordLocked(null, info, null, isolated);
6434 mProcessNames.put(info.processName, app.uid, app);
6435 if (isolated) {
6436 mIsolatedProcesses.put(app.uid, app);
6437 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006438 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
6440
Dianne Hackborne7f97212011-02-24 14:40:20 -08006441 // This package really, really can not be stopped.
6442 try {
6443 AppGlobals.getPackageManager().setPackageStoppedState(
6444 info.packageName, false);
6445 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006446 } catch (IllegalArgumentException e) {
6447 Slog.w(TAG, "Failed trying to unstop package "
6448 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006449 }
6450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6452 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6453 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006454 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 }
6456 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6457 mPersistentStartingProcesses.add(app);
6458 startProcessLocked(app, "added application", app.processName);
6459 }
6460
6461 return app;
6462 }
6463
6464 public void unhandledBack() {
6465 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6466 "unhandledBack()");
6467
6468 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006469 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006470 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 TAG, "Performing unhandledBack(): stack size = " + count);
6472 if (count > 1) {
6473 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006474 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6476 Binder.restoreCallingIdentity(origId);
6477 }
6478 }
6479 }
6480
6481 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006482 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006484 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 ParcelFileDescriptor pfd = null;
6486 if (cph != null) {
6487 // We record the binder invoker's uid in thread-local storage before
6488 // going to the content provider to open the file. Later, in the code
6489 // that handles all permissions checks, we look for this uid and use
6490 // that rather than the Activity Manager's own uid. The effect is that
6491 // we do the check against the caller's permissions even though it looks
6492 // to the content provider like the Activity Manager itself is making
6493 // the request.
6494 sCallerIdentity.set(new Identity(
6495 Binder.getCallingPid(), Binder.getCallingUid()));
6496 try {
6497 pfd = cph.provider.openFile(uri, "r");
6498 } catch (FileNotFoundException e) {
6499 // do nothing; pfd will be returned null
6500 } finally {
6501 // Ensure that whatever happens, we clean up the identity state
6502 sCallerIdentity.remove();
6503 }
6504
6505 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006506 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006508 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 }
6510 return pfd;
6511 }
6512
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006513 // Actually is sleeping or shutting down or whatever else in the future
6514 // is an inactive state.
6515 public boolean isSleeping() {
6516 return mSleeping || mShuttingDown;
6517 }
6518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 public void goingToSleep() {
6520 synchronized(this) {
6521 mSleeping = true;
6522 mWindowManager.setEventDispatching(false);
6523
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006524 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006525
6526 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006527 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006528 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6529 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006530 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 }
6532 }
6533
Dianne Hackborn55280a92009-05-07 15:53:46 -07006534 public boolean shutdown(int timeout) {
6535 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6536 != PackageManager.PERMISSION_GRANTED) {
6537 throw new SecurityException("Requires permission "
6538 + android.Manifest.permission.SHUTDOWN);
6539 }
6540
6541 boolean timedout = false;
6542
6543 synchronized(this) {
6544 mShuttingDown = true;
6545 mWindowManager.setEventDispatching(false);
6546
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006547 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006548 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006549 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006550 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006551 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006552 long delay = endTime - System.currentTimeMillis();
6553 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006554 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006555 timedout = true;
6556 break;
6557 }
6558 try {
6559 this.wait();
6560 } catch (InterruptedException e) {
6561 }
6562 }
6563 }
6564 }
6565
6566 mUsageStatsService.shutdown();
6567 mBatteryStatsService.shutdown();
6568
6569 return timedout;
6570 }
6571
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006572 public final void activitySlept(IBinder token) {
6573 if (localLOGV) Slog.v(
6574 TAG, "Activity slept: token=" + token);
6575
6576 ActivityRecord r = null;
6577
6578 final long origId = Binder.clearCallingIdentity();
6579
6580 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006581 r = mMainStack.isInStackLocked(token);
6582 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006583 mMainStack.activitySleptLocked(r);
6584 }
6585 }
6586
6587 Binder.restoreCallingIdentity(origId);
6588 }
6589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 public void wakingUp() {
6591 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 mWindowManager.setEventDispatching(true);
6593 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006594 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006595 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 }
6597 }
6598
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006599 public void stopAppSwitches() {
6600 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6601 != PackageManager.PERMISSION_GRANTED) {
6602 throw new SecurityException("Requires permission "
6603 + android.Manifest.permission.STOP_APP_SWITCHES);
6604 }
6605
6606 synchronized(this) {
6607 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6608 + APP_SWITCH_DELAY_TIME;
6609 mDidAppSwitch = false;
6610 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6611 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6612 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6613 }
6614 }
6615
6616 public void resumeAppSwitches() {
6617 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6618 != PackageManager.PERMISSION_GRANTED) {
6619 throw new SecurityException("Requires permission "
6620 + android.Manifest.permission.STOP_APP_SWITCHES);
6621 }
6622
6623 synchronized(this) {
6624 // Note that we don't execute any pending app switches... we will
6625 // let those wait until either the timeout, or the next start
6626 // activity request.
6627 mAppSwitchesAllowedTime = 0;
6628 }
6629 }
6630
6631 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6632 String name) {
6633 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6634 return true;
6635 }
6636
6637 final int perm = checkComponentPermission(
6638 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006639 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006640 if (perm == PackageManager.PERMISSION_GRANTED) {
6641 return true;
6642 }
6643
Joe Onorato8a9b2202010-02-26 18:56:32 -08006644 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006645 return false;
6646 }
6647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 public void setDebugApp(String packageName, boolean waitForDebugger,
6649 boolean persistent) {
6650 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6651 "setDebugApp()");
6652
6653 // Note that this is not really thread safe if there are multiple
6654 // callers into it at the same time, but that's not a situation we
6655 // care about.
6656 if (persistent) {
6657 final ContentResolver resolver = mContext.getContentResolver();
6658 Settings.System.putString(
6659 resolver, Settings.System.DEBUG_APP,
6660 packageName);
6661 Settings.System.putInt(
6662 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6663 waitForDebugger ? 1 : 0);
6664 }
6665
6666 synchronized (this) {
6667 if (!persistent) {
6668 mOrigDebugApp = mDebugApp;
6669 mOrigWaitForDebugger = mWaitForDebugger;
6670 }
6671 mDebugApp = packageName;
6672 mWaitForDebugger = waitForDebugger;
6673 mDebugTransient = !persistent;
6674 if (packageName != null) {
6675 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006676 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 Binder.restoreCallingIdentity(origId);
6678 }
6679 }
6680 }
6681
Siva Velusamy92a8b222012-03-09 16:24:04 -08006682 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6683 synchronized (this) {
6684 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6685 if (!isDebuggable) {
6686 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6687 throw new SecurityException("Process not debuggable: " + app.packageName);
6688 }
6689 }
6690
6691 mOpenGlTraceApp = processName;
6692 }
6693 }
6694
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006695 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6696 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6697 synchronized (this) {
6698 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6699 if (!isDebuggable) {
6700 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6701 throw new SecurityException("Process not debuggable: " + app.packageName);
6702 }
6703 }
6704 mProfileApp = processName;
6705 mProfileFile = profileFile;
6706 if (mProfileFd != null) {
6707 try {
6708 mProfileFd.close();
6709 } catch (IOException e) {
6710 }
6711 mProfileFd = null;
6712 }
6713 mProfileFd = profileFd;
6714 mProfileType = 0;
6715 mAutoStopProfiler = autoStopProfiler;
6716 }
6717 }
6718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 public void setAlwaysFinish(boolean enabled) {
6720 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6721 "setAlwaysFinish()");
6722
6723 Settings.System.putInt(
6724 mContext.getContentResolver(),
6725 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6726
6727 synchronized (this) {
6728 mAlwaysFinishActivities = enabled;
6729 }
6730 }
6731
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006732 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006734 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006736 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 }
6738 }
6739
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006740 public boolean isUserAMonkey() {
6741 // For now the fact that there is a controller implies
6742 // we have a monkey.
6743 synchronized (this) {
6744 return mController != null;
6745 }
6746 }
6747
Jeff Sharkeya4620792011-05-20 15:29:23 -07006748 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006749 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6750 "registerProcessObserver()");
6751 synchronized (this) {
6752 mProcessObservers.register(observer);
6753 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006754 }
6755
6756 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006757 synchronized (this) {
6758 mProcessObservers.unregister(observer);
6759 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006760 }
6761
Daniel Sandler69a48172010-06-23 16:29:36 -04006762 public void setImmersive(IBinder token, boolean immersive) {
6763 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006764 ActivityRecord r = mMainStack.isInStackLocked(token);
6765 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006766 throw new IllegalArgumentException();
6767 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006768 r.immersive = immersive;
6769 }
6770 }
6771
6772 public boolean isImmersive(IBinder token) {
6773 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006774 ActivityRecord r = mMainStack.isInStackLocked(token);
6775 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006776 throw new IllegalArgumentException();
6777 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006778 return r.immersive;
6779 }
6780 }
6781
6782 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006783 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006784 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006785 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006786 return (r != null) ? r.immersive : false;
6787 }
6788 }
6789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006790 public final void enterSafeMode() {
6791 synchronized(this) {
6792 // It only makes sense to do this before the system is ready
6793 // and started launching other packages.
6794 if (!mSystemReady) {
6795 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006796 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 } catch (RemoteException e) {
6798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 }
6800 }
6801 }
6802
Jeff Brownb09abc12011-01-13 21:08:27 -08006803 public final void showSafeModeOverlay() {
6804 View v = LayoutInflater.from(mContext).inflate(
6805 com.android.internal.R.layout.safe_mode, null);
6806 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6807 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6808 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6809 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6810 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6811 lp.format = v.getBackground().getOpacity();
6812 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6813 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6814 ((WindowManager)mContext.getSystemService(
6815 Context.WINDOW_SERVICE)).addView(v, lp);
6816 }
6817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 public void noteWakeupAlarm(IIntentSender sender) {
6819 if (!(sender instanceof PendingIntentRecord)) {
6820 return;
6821 }
6822 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6823 synchronized (stats) {
6824 if (mBatteryStatsService.isOnBattery()) {
6825 mBatteryStatsService.enforceCallingPermission();
6826 PendingIntentRecord rec = (PendingIntentRecord)sender;
6827 int MY_UID = Binder.getCallingUid();
6828 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6829 BatteryStatsImpl.Uid.Pkg pkg =
6830 stats.getPackageStatsLocked(uid, rec.key.packageName);
6831 pkg.incWakeupsLocked();
6832 }
6833 }
6834 }
6835
Dianne Hackborn64825172011-03-02 21:32:58 -08006836 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006838 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006840 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 // XXX Note: don't acquire main activity lock here, because the window
6842 // manager calls in with its locks held.
6843
6844 boolean killed = false;
6845 synchronized (mPidsSelfLocked) {
6846 int[] types = new int[pids.length];
6847 int worstType = 0;
6848 for (int i=0; i<pids.length; i++) {
6849 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6850 if (proc != null) {
6851 int type = proc.setAdj;
6852 types[i] = type;
6853 if (type > worstType) {
6854 worstType = type;
6855 }
6856 }
6857 }
6858
Dianne Hackborn64825172011-03-02 21:32:58 -08006859 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006860 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006861 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6862 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006863 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006865
6866 // If this is not a secure call, don't let it kill processes that
6867 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006868 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6869 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006870 }
6871
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006872 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 for (int i=0; i<pids.length; i++) {
6874 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6875 if (proc == null) {
6876 continue;
6877 }
6878 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006879 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006880 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006881 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6882 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006884 proc.killedBackground = true;
6885 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 }
6887 }
6888 }
6889 return killed;
6890 }
6891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 public final void startRunning(String pkg, String cls, String action,
6893 String data) {
6894 synchronized(this) {
6895 if (mStartRunning) {
6896 return;
6897 }
6898 mStartRunning = true;
6899 mTopComponent = pkg != null && cls != null
6900 ? new ComponentName(pkg, cls) : null;
6901 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6902 mTopData = data;
6903 if (!mSystemReady) {
6904 return;
6905 }
6906 }
6907
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006908 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 }
6910
6911 private void retrieveSettings() {
6912 final ContentResolver resolver = mContext.getContentResolver();
6913 String debugApp = Settings.System.getString(
6914 resolver, Settings.System.DEBUG_APP);
6915 boolean waitForDebugger = Settings.System.getInt(
6916 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6917 boolean alwaysFinishActivities = Settings.System.getInt(
6918 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6919
6920 Configuration configuration = new Configuration();
6921 Settings.System.getConfiguration(resolver, configuration);
6922
6923 synchronized (this) {
6924 mDebugApp = mOrigDebugApp = debugApp;
6925 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6926 mAlwaysFinishActivities = alwaysFinishActivities;
6927 // This happens before any activities are started, so we can
6928 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006929 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006930 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 }
6932 }
6933
6934 public boolean testIsSystemReady() {
6935 // no need to synchronize(this) just to read & return the value
6936 return mSystemReady;
6937 }
6938
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006939 private static File getCalledPreBootReceiversFile() {
6940 File dataDir = Environment.getDataDirectory();
6941 File systemDir = new File(dataDir, "system");
6942 File fname = new File(systemDir, "called_pre_boots.dat");
6943 return fname;
6944 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006945
6946 static final int LAST_DONE_VERSION = 10000;
6947
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006948 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6949 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6950 File file = getCalledPreBootReceiversFile();
6951 FileInputStream fis = null;
6952 try {
6953 fis = new FileInputStream(file);
6954 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006955 int fvers = dis.readInt();
6956 if (fvers == LAST_DONE_VERSION) {
6957 String vers = dis.readUTF();
6958 String codename = dis.readUTF();
6959 String build = dis.readUTF();
6960 if (android.os.Build.VERSION.RELEASE.equals(vers)
6961 && android.os.Build.VERSION.CODENAME.equals(codename)
6962 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6963 int num = dis.readInt();
6964 while (num > 0) {
6965 num--;
6966 String pkg = dis.readUTF();
6967 String cls = dis.readUTF();
6968 lastDoneReceivers.add(new ComponentName(pkg, cls));
6969 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006970 }
6971 }
6972 } catch (FileNotFoundException e) {
6973 } catch (IOException e) {
6974 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6975 } finally {
6976 if (fis != null) {
6977 try {
6978 fis.close();
6979 } catch (IOException e) {
6980 }
6981 }
6982 }
6983 return lastDoneReceivers;
6984 }
6985
6986 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6987 File file = getCalledPreBootReceiversFile();
6988 FileOutputStream fos = null;
6989 DataOutputStream dos = null;
6990 try {
6991 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6992 fos = new FileOutputStream(file);
6993 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006994 dos.writeInt(LAST_DONE_VERSION);
6995 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006996 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006997 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006998 dos.writeInt(list.size());
6999 for (int i=0; i<list.size(); i++) {
7000 dos.writeUTF(list.get(i).getPackageName());
7001 dos.writeUTF(list.get(i).getClassName());
7002 }
7003 } catch (IOException e) {
7004 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7005 file.delete();
7006 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007007 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007008 if (dos != null) {
7009 try {
7010 dos.close();
7011 } catch (IOException e) {
7012 // TODO Auto-generated catch block
7013 e.printStackTrace();
7014 }
7015 }
7016 }
7017 }
7018
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007019 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007020 synchronized(this) {
7021 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007022 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 return;
7024 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007025
7026 // Check to see if there are any update receivers to run.
7027 if (!mDidUpdate) {
7028 if (mWaitingUpdate) {
7029 return;
7030 }
7031 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7032 List<ResolveInfo> ris = null;
7033 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007034 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007035 intent, null, 0);
7036 } catch (RemoteException e) {
7037 }
7038 if (ris != null) {
7039 for (int i=ris.size()-1; i>=0; i--) {
7040 if ((ris.get(i).activityInfo.applicationInfo.flags
7041 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7042 ris.remove(i);
7043 }
7044 }
7045 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007046
7047 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7048
7049 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007050 for (int i=0; i<ris.size(); i++) {
7051 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007052 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7053 if (lastDoneReceivers.contains(comp)) {
7054 ris.remove(i);
7055 i--;
7056 }
7057 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007058
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007059 for (int i=0; i<ris.size(); i++) {
7060 ActivityInfo ai = ris.get(i).activityInfo;
7061 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7062 doneReceivers.add(comp);
7063 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007064 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007065 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007066 finisher = new IIntentReceiver.Stub() {
7067 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007068 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007069 boolean sticky) {
7070 // The raw IIntentReceiver interface is called
7071 // with the AM lock held, so redispatch to
7072 // execute our code without the lock.
7073 mHandler.post(new Runnable() {
7074 public void run() {
7075 synchronized (ActivityManagerService.this) {
7076 mDidUpdate = true;
7077 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007078 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007079 showBootMessage(mContext.getText(
7080 R.string.android_upgrading_complete),
7081 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007082 systemReady(goingCallback);
7083 }
7084 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007085 }
7086 };
7087 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007088 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007089 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007090 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007091 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007092 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007093 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007094 mWaitingUpdate = true;
7095 }
7096 }
7097 }
7098 if (mWaitingUpdate) {
7099 return;
7100 }
7101 mDidUpdate = true;
7102 }
7103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 mSystemReady = true;
7105 if (!mStartRunning) {
7106 return;
7107 }
7108 }
7109
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007110 ArrayList<ProcessRecord> procsToKill = null;
7111 synchronized(mPidsSelfLocked) {
7112 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7113 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7114 if (!isAllowedWhileBooting(proc.info)){
7115 if (procsToKill == null) {
7116 procsToKill = new ArrayList<ProcessRecord>();
7117 }
7118 procsToKill.add(proc);
7119 }
7120 }
7121 }
7122
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007123 synchronized(this) {
7124 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007125 for (int i=procsToKill.size()-1; i>=0; i--) {
7126 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007127 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007128 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007129 }
7130 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007131
7132 // Now that we have cleaned up any update processes, we
7133 // are ready to start launching real processes and know that
7134 // we won't trample on them any more.
7135 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007136 }
7137
Joe Onorato8a9b2202010-02-26 18:56:32 -08007138 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007139 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 SystemClock.uptimeMillis());
7141
7142 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007143 // Make sure we have no pre-ready processes sitting around.
7144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7146 ResolveInfo ri = mContext.getPackageManager()
7147 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007148 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 CharSequence errorMsg = null;
7150 if (ri != null) {
7151 ActivityInfo ai = ri.activityInfo;
7152 ApplicationInfo app = ai.applicationInfo;
7153 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7154 mTopAction = Intent.ACTION_FACTORY_TEST;
7155 mTopData = null;
7156 mTopComponent = new ComponentName(app.packageName,
7157 ai.name);
7158 } else {
7159 errorMsg = mContext.getResources().getText(
7160 com.android.internal.R.string.factorytest_not_system);
7161 }
7162 } else {
7163 errorMsg = mContext.getResources().getText(
7164 com.android.internal.R.string.factorytest_no_action);
7165 }
7166 if (errorMsg != null) {
7167 mTopAction = null;
7168 mTopData = null;
7169 mTopComponent = null;
7170 Message msg = Message.obtain();
7171 msg.what = SHOW_FACTORY_ERROR_MSG;
7172 msg.getData().putCharSequence("msg", errorMsg);
7173 mHandler.sendMessage(msg);
7174 }
7175 }
7176 }
7177
7178 retrieveSettings();
7179
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007180 if (goingCallback != null) goingCallback.run();
7181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 synchronized (this) {
7183 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7184 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007185 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007186 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 if (apps != null) {
7188 int N = apps.size();
7189 int i;
7190 for (i=0; i<N; i++) {
7191 ApplicationInfo info
7192 = (ApplicationInfo)apps.get(i);
7193 if (info != null &&
7194 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007195 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197 }
7198 }
7199 } catch (RemoteException ex) {
7200 // pm is in same process, this will never happen.
7201 }
7202 }
7203
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007204 // Start up initial activity.
7205 mBooting = true;
7206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007207 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007208 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 Message msg = Message.obtain();
7210 msg.what = SHOW_UID_ERROR_MSG;
7211 mHandler.sendMessage(msg);
7212 }
7213 } catch (RemoteException e) {
7214 }
7215
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007216 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 }
7218 }
7219
Dan Egnorb7f03672009-12-09 16:22:32 -08007220 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007221 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007222 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007223 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007224 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007225 startAppProblemLocked(app);
7226 app.stopFreezingAllLocked();
7227 return handleAppCrashLocked(app);
7228 }
7229
Dan Egnorb7f03672009-12-09 16:22:32 -08007230 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007231 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007233 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007234 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7235 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 startAppProblemLocked(app);
7237 app.stopFreezingAllLocked();
7238 }
7239
7240 /**
7241 * Generate a process error record, suitable for attachment to a ProcessRecord.
7242 *
7243 * @param app The ProcessRecord in which the error occurred.
7244 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7245 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007246 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 * @param shortMsg Short message describing the crash.
7248 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007249 * @param stackTrace Full crash stack trace, may be null.
7250 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007251 * @return Returns a fully-formed AppErrorStateInfo record.
7252 */
7253 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007254 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257 report.condition = condition;
7258 report.processName = app.processName;
7259 report.pid = app.pid;
7260 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007261 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 report.shortMsg = shortMsg;
7263 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007264 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265
7266 return report;
7267 }
7268
Dan Egnor42471dd2010-01-07 17:25:22 -08007269 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 synchronized (this) {
7271 app.crashing = false;
7272 app.crashingReport = null;
7273 app.notResponding = false;
7274 app.notRespondingReport = null;
7275 if (app.anrDialog == fromDialog) {
7276 app.anrDialog = null;
7277 }
7278 if (app.waitDialog == fromDialog) {
7279 app.waitDialog = null;
7280 }
7281 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007282 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007283 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007284 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7285 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007286 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 }
7289 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007290
Dan Egnorb7f03672009-12-09 16:22:32 -08007291 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 long now = SystemClock.uptimeMillis();
7293
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007294 Long crashTime;
7295 if (!app.isolated) {
7296 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7297 } else {
7298 crashTime = null;
7299 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007300 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007302 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007304 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007305 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007306 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7307 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007309 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007311 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007312 }
7313 }
7314 if (!app.persistent) {
7315 // We don't want to start this process again until the user
7316 // explicitly does so... but for persistent process, we really
7317 // need to keep it running. If a persistent process is actually
7318 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007319 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007321 if (!app.isolated) {
7322 // XXX We don't have a way to mark isolated processes
7323 // as bad, since they don't have a peristent identity.
7324 mBadProcesses.put(app.info.processName, app.uid, now);
7325 mProcessCrashTimes.remove(app.info.processName, app.uid);
7326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007328 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007329 // Don't let services in this process be restarted and potentially
7330 // annoy the user repeatedly. Unless it is persistent, since those
7331 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007332 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007333 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 return false;
7335 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007336 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007337 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007338 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007339 if (r.app == app) {
7340 // If the top running activity is from this crashing
7341 // process, then terminate it to avoid getting in a loop.
7342 Slog.w(TAG, " Force finishing activity "
7343 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007344 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007345 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007346 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007347 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007348 // stopped, to avoid a situation where one will get
7349 // re-start our crashing activity once it gets resumed again.
7350 index--;
7351 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007352 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007353 if (r.state == ActivityState.RESUMED
7354 || r.state == ActivityState.PAUSING
7355 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007356 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007357 Slog.w(TAG, " Force finishing activity "
7358 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007359 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007360 Activity.RESULT_CANCELED, null, "crashed");
7361 }
7362 }
7363 }
7364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007365 }
7366
7367 // Bump up the crash count of any services currently running in the proc.
7368 if (app.services.size() != 0) {
7369 // Any services running in the application need to be placed
7370 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007371 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007372 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007373 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007374 sr.crashCount++;
7375 }
7376 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007377
7378 // If the crashing process is what we consider to be the "home process" and it has been
7379 // replaced by a third-party app, clear the package preferred activities from packages
7380 // with a home activity running in the process to prevent a repeatedly crashing app
7381 // from blocking the user to manually clear the list.
7382 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7383 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7384 Iterator it = mHomeProcess.activities.iterator();
7385 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007386 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007387 if (r.isHomeActivity) {
7388 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7389 try {
7390 ActivityThread.getPackageManager()
7391 .clearPackagePreferredActivities(r.packageName);
7392 } catch (RemoteException c) {
7393 // pm is in same process, this will never happen.
7394 }
7395 }
7396 }
7397 }
7398
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007399 if (!app.isolated) {
7400 // XXX Can't keep track of crash times for isolated processes,
7401 // because they don't have a perisistent identity.
7402 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7403 }
7404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 return true;
7406 }
7407
7408 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007409 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7410 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 skipCurrentReceiverLocked(app);
7412 }
7413
7414 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007415 for (BroadcastQueue queue : mBroadcastQueues) {
7416 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 }
7418 }
7419
Dan Egnor60d87622009-12-16 16:32:58 -08007420 /**
7421 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7422 * The application process will exit immediately after this call returns.
7423 * @param app object of the crashing app, null for the system server
7424 * @param crashInfo describing the exception
7425 */
7426 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007427 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007428 final String processName = app == null ? "system_server"
7429 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007430
7431 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007432 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007433 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007434 crashInfo.exceptionClassName,
7435 crashInfo.exceptionMessage,
7436 crashInfo.throwFileName,
7437 crashInfo.throwLineNumber);
7438
Jeff Sharkeya353d262011-10-28 11:12:06 -07007439 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007440
7441 crashApplication(r, crashInfo);
7442 }
7443
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007444 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007445 IBinder app,
7446 int violationMask,
7447 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007448 ProcessRecord r = findAppProcess(app, "StrictMode");
7449 if (r == null) {
7450 return;
7451 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007452
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007453 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007454 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007455 boolean logIt = true;
7456 synchronized (mAlreadyLoggedViolatedStacks) {
7457 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7458 logIt = false;
7459 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007460 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007461 // the relative pain numbers, without logging all
7462 // the stack traces repeatedly. We'd want to do
7463 // likewise in the client code, which also does
7464 // dup suppression, before the Binder call.
7465 } else {
7466 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7467 mAlreadyLoggedViolatedStacks.clear();
7468 }
7469 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7470 }
7471 }
7472 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007473 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007474 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007475 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007476
7477 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7478 AppErrorResult result = new AppErrorResult();
7479 synchronized (this) {
7480 final long origId = Binder.clearCallingIdentity();
7481
7482 Message msg = Message.obtain();
7483 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7484 HashMap<String, Object> data = new HashMap<String, Object>();
7485 data.put("result", result);
7486 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007487 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007488 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007489 msg.obj = data;
7490 mHandler.sendMessage(msg);
7491
7492 Binder.restoreCallingIdentity(origId);
7493 }
7494 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007495 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007496 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007497 }
7498
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007499 // Depending on the policy in effect, there could be a bunch of
7500 // these in quick succession so we try to batch these together to
7501 // minimize disk writes, number of dropbox entries, and maximize
7502 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007503 private void logStrictModeViolationToDropBox(
7504 ProcessRecord process,
7505 StrictMode.ViolationInfo info) {
7506 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007507 return;
7508 }
7509 final boolean isSystemApp = process == null ||
7510 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7511 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007512 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007513 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7514 final DropBoxManager dbox = (DropBoxManager)
7515 mContext.getSystemService(Context.DROPBOX_SERVICE);
7516
7517 // Exit early if the dropbox isn't configured to accept this report type.
7518 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7519
7520 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007521 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007522 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7523 synchronized (sb) {
7524 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007525 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007526 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7527 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007528 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7529 if (info.violationNumThisLoop != 0) {
7530 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7531 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007532 if (info.numAnimationsRunning != 0) {
7533 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7534 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007535 if (info.broadcastIntentAction != null) {
7536 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7537 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007538 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007539 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007540 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007541 if (info.numInstances != -1) {
7542 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7543 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007544 if (info.tags != null) {
7545 for (String tag : info.tags) {
7546 sb.append("Span-Tag: ").append(tag).append("\n");
7547 }
7548 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007549 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007550 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7551 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007552 }
7553 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007554
7555 // Only buffer up to ~64k. Various logging bits truncate
7556 // things at 128k.
7557 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007558 }
7559
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007560 // Flush immediately if the buffer's grown too large, or this
7561 // is a non-system app. Non-system apps are isolated with a
7562 // different tag & policy and not batched.
7563 //
7564 // Batching is useful during internal testing with
7565 // StrictMode settings turned up high. Without batching,
7566 // thousands of separate files could be created on boot.
7567 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007568 new Thread("Error dump: " + dropboxTag) {
7569 @Override
7570 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007571 String report;
7572 synchronized (sb) {
7573 report = sb.toString();
7574 sb.delete(0, sb.length());
7575 sb.trimToSize();
7576 }
7577 if (report.length() != 0) {
7578 dbox.addText(dropboxTag, report);
7579 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007580 }
7581 }.start();
7582 return;
7583 }
7584
7585 // System app batching:
7586 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007587 // An existing dropbox-writing thread is outstanding, so
7588 // we don't need to start it up. The existing thread will
7589 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007590 return;
7591 }
7592
7593 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7594 // (After this point, we shouldn't access AMS internal data structures.)
7595 new Thread("Error dump: " + dropboxTag) {
7596 @Override
7597 public void run() {
7598 // 5 second sleep to let stacks arrive and be batched together
7599 try {
7600 Thread.sleep(5000); // 5 seconds
7601 } catch (InterruptedException e) {}
7602
7603 String errorReport;
7604 synchronized (mStrictModeBuffer) {
7605 errorReport = mStrictModeBuffer.toString();
7606 if (errorReport.length() == 0) {
7607 return;
7608 }
7609 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7610 mStrictModeBuffer.trimToSize();
7611 }
7612 dbox.addText(dropboxTag, errorReport);
7613 }
7614 }.start();
7615 }
7616
Dan Egnor60d87622009-12-16 16:32:58 -08007617 /**
7618 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7619 * @param app object of the crashing app, null for the system server
7620 * @param tag reported by the caller
7621 * @param crashInfo describing the context of the error
7622 * @return true if the process should exit immediately (WTF is fatal)
7623 */
7624 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007625 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007626 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007627 final String processName = app == null ? "system_server"
7628 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007629
7630 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007631 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007632 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007633 tag, crashInfo.exceptionMessage);
7634
Jeff Sharkeya353d262011-10-28 11:12:06 -07007635 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007636
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007637 if (r != null && r.pid != Process.myPid() &&
7638 Settings.Secure.getInt(mContext.getContentResolver(),
7639 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007640 crashApplication(r, crashInfo);
7641 return true;
7642 } else {
7643 return false;
7644 }
7645 }
7646
7647 /**
7648 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7649 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7650 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007651 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007652 if (app == null) {
7653 return null;
7654 }
7655
7656 synchronized (this) {
7657 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7658 final int NA = apps.size();
7659 for (int ia=0; ia<NA; ia++) {
7660 ProcessRecord p = apps.valueAt(ia);
7661 if (p.thread != null && p.thread.asBinder() == app) {
7662 return p;
7663 }
7664 }
7665 }
7666
Dianne Hackborncb44d962011-03-10 17:02:27 -08007667 Slog.w(TAG, "Can't find mystery application for " + reason
7668 + " from pid=" + Binder.getCallingPid()
7669 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007670 return null;
7671 }
7672 }
7673
7674 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007675 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7676 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007677 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007678 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7679 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007680 // Watchdog thread ends up invoking this function (with
7681 // a null ProcessRecord) to add the stack file to dropbox.
7682 // Do not acquire a lock on this (am) in such cases, as it
7683 // could cause a potential deadlock, if and when watchdog
7684 // is invoked due to unavailability of lock on am and it
7685 // would prevent watchdog from killing system_server.
7686 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007687 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007688 return;
7689 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007690 // Note: ProcessRecord 'process' is guarded by the service
7691 // instance. (notably process.pkgList, which could otherwise change
7692 // concurrently during execution of this method)
7693 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007694 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007695 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007696 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007697 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7698 for (String pkg : process.pkgList) {
7699 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007700 try {
Dan Egnora455d192010-03-12 08:52:28 -08007701 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7702 if (pi != null) {
7703 sb.append(" v").append(pi.versionCode);
7704 if (pi.versionName != null) {
7705 sb.append(" (").append(pi.versionName).append(")");
7706 }
7707 }
7708 } catch (RemoteException e) {
7709 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007710 }
Dan Egnora455d192010-03-12 08:52:28 -08007711 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007712 }
Dan Egnora455d192010-03-12 08:52:28 -08007713 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007714 }
7715
7716 private static String processClass(ProcessRecord process) {
7717 if (process == null || process.pid == MY_PID) {
7718 return "system_server";
7719 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7720 return "system_app";
7721 } else {
7722 return "data_app";
7723 }
7724 }
7725
7726 /**
7727 * Write a description of an error (crash, WTF, ANR) to the drop box.
7728 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7729 * @param process which caused the error, null means the system server
7730 * @param activity which triggered the error, null if unknown
7731 * @param parent activity related to the error, null if unknown
7732 * @param subject line related to the error, null if absent
7733 * @param report in long form describing the error, null if absent
7734 * @param logFile to include in the report, null if none
7735 * @param crashInfo giving an application stack trace, null if absent
7736 */
7737 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007738 ProcessRecord process, String processName, ActivityRecord activity,
7739 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007740 final String report, final File logFile,
7741 final ApplicationErrorReport.CrashInfo crashInfo) {
7742 // NOTE -- this must never acquire the ActivityManagerService lock,
7743 // otherwise the watchdog may be prevented from resetting the system.
7744
7745 final String dropboxTag = processClass(process) + "_" + eventType;
7746 final DropBoxManager dbox = (DropBoxManager)
7747 mContext.getSystemService(Context.DROPBOX_SERVICE);
7748
7749 // Exit early if the dropbox isn't configured to accept this report type.
7750 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7751
7752 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007753 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007754 if (activity != null) {
7755 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7756 }
7757 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7758 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7759 }
7760 if (parent != null && parent != activity) {
7761 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7762 }
7763 if (subject != null) {
7764 sb.append("Subject: ").append(subject).append("\n");
7765 }
7766 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007767 if (Debug.isDebuggerConnected()) {
7768 sb.append("Debugger: Connected\n");
7769 }
Dan Egnora455d192010-03-12 08:52:28 -08007770 sb.append("\n");
7771
7772 // Do the rest in a worker thread to avoid blocking the caller on I/O
7773 // (After this point, we shouldn't access AMS internal data structures.)
7774 Thread worker = new Thread("Error dump: " + dropboxTag) {
7775 @Override
7776 public void run() {
7777 if (report != null) {
7778 sb.append(report);
7779 }
7780 if (logFile != null) {
7781 try {
7782 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7783 } catch (IOException e) {
7784 Slog.e(TAG, "Error reading " + logFile, e);
7785 }
7786 }
7787 if (crashInfo != null && crashInfo.stackTrace != null) {
7788 sb.append(crashInfo.stackTrace);
7789 }
7790
7791 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7792 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7793 if (lines > 0) {
7794 sb.append("\n");
7795
7796 // Merge several logcat streams, and take the last N lines
7797 InputStreamReader input = null;
7798 try {
7799 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7800 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7801 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7802
7803 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7804 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7805 input = new InputStreamReader(logcat.getInputStream());
7806
7807 int num;
7808 char[] buf = new char[8192];
7809 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7810 } catch (IOException e) {
7811 Slog.e(TAG, "Error running logcat", e);
7812 } finally {
7813 if (input != null) try { input.close(); } catch (IOException e) {}
7814 }
7815 }
7816
7817 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007818 }
Dan Egnora455d192010-03-12 08:52:28 -08007819 };
7820
7821 if (process == null || process.pid == MY_PID) {
7822 worker.run(); // We may be about to die -- need to run this synchronously
7823 } else {
7824 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007825 }
7826 }
7827
7828 /**
7829 * Bring up the "unexpected error" dialog box for a crashing app.
7830 * Deal with edge cases (intercepts from instrumented applications,
7831 * ActivityController, error intent receivers, that sort of thing).
7832 * @param r the application crashing
7833 * @param crashInfo describing the failure
7834 */
7835 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007836 long timeMillis = System.currentTimeMillis();
7837 String shortMsg = crashInfo.exceptionClassName;
7838 String longMsg = crashInfo.exceptionMessage;
7839 String stackTrace = crashInfo.stackTrace;
7840 if (shortMsg != null && longMsg != null) {
7841 longMsg = shortMsg + ": " + longMsg;
7842 } else if (shortMsg != null) {
7843 longMsg = shortMsg;
7844 }
7845
Dan Egnor60d87622009-12-16 16:32:58 -08007846 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007848 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 try {
7850 String name = r != null ? r.processName : null;
7851 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007852 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007853 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007854 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007855 + " at watcher's request");
7856 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007857 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 }
7859 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007860 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 }
7862 }
7863
7864 final long origId = Binder.clearCallingIdentity();
7865
7866 // If this process is running instrumentation, finish it.
7867 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007868 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007870 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7871 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 Bundle info = new Bundle();
7873 info.putString("shortMsg", shortMsg);
7874 info.putString("longMsg", longMsg);
7875 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7876 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007877 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 }
7879
Dan Egnor60d87622009-12-16 16:32:58 -08007880 // If we can't identify the process or it's already exceeded its crash quota,
7881 // quit right away without showing a crash dialog.
7882 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007884 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 }
7886
7887 Message msg = Message.obtain();
7888 msg.what = SHOW_ERROR_MSG;
7889 HashMap data = new HashMap();
7890 data.put("result", result);
7891 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 msg.obj = data;
7893 mHandler.sendMessage(msg);
7894
7895 Binder.restoreCallingIdentity(origId);
7896 }
7897
7898 int res = result.get();
7899
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007900 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007902 if (r != null && !r.isolated) {
7903 // XXX Can't keep track of crash time for isolated processes,
7904 // since they don't have a persistent identity.
7905 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 SystemClock.uptimeMillis());
7907 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007908 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007909 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007910 }
7911 }
7912
7913 if (appErrorIntent != null) {
7914 try {
7915 mContext.startActivity(appErrorIntent);
7916 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007917 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007921
7922 Intent createAppErrorIntentLocked(ProcessRecord r,
7923 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7924 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007925 if (report == null) {
7926 return null;
7927 }
7928 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7929 result.setComponent(r.errorReportReceiver);
7930 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7931 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7932 return result;
7933 }
7934
Dan Egnorb7f03672009-12-09 16:22:32 -08007935 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7936 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007937 if (r.errorReportReceiver == null) {
7938 return null;
7939 }
7940
7941 if (!r.crashing && !r.notResponding) {
7942 return null;
7943 }
7944
Dan Egnorb7f03672009-12-09 16:22:32 -08007945 ApplicationErrorReport report = new ApplicationErrorReport();
7946 report.packageName = r.info.packageName;
7947 report.installerPackageName = r.errorReportReceiver.getPackageName();
7948 report.processName = r.processName;
7949 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007950 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007951
Dan Egnorb7f03672009-12-09 16:22:32 -08007952 if (r.crashing) {
7953 report.type = ApplicationErrorReport.TYPE_CRASH;
7954 report.crashInfo = crashInfo;
7955 } else if (r.notResponding) {
7956 report.type = ApplicationErrorReport.TYPE_ANR;
7957 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007958
Dan Egnorb7f03672009-12-09 16:22:32 -08007959 report.anrInfo.activity = r.notRespondingReport.tag;
7960 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7961 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007962 }
7963
Dan Egnorb7f03672009-12-09 16:22:32 -08007964 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007965 }
7966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007968 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 // assume our apps are happy - lazy create the list
7970 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7971
7972 synchronized (this) {
7973
7974 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007975 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7976 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7978 // This one's in trouble, so we'll generate a report for it
7979 // crashes are higher priority (in case there's a crash *and* an anr)
7980 ActivityManager.ProcessErrorStateInfo report = null;
7981 if (app.crashing) {
7982 report = app.crashingReport;
7983 } else if (app.notResponding) {
7984 report = app.notRespondingReport;
7985 }
7986
7987 if (report != null) {
7988 if (errList == null) {
7989 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7990 }
7991 errList.add(report);
7992 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007993 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 " crashing = " + app.crashing +
7995 " notResponding = " + app.notResponding);
7996 }
7997 }
7998 }
7999 }
8000
8001 return errList;
8002 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008003
8004 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008005 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008006 if (currApp != null) {
8007 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8008 }
8009 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008010 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8011 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008012 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8013 if (currApp != null) {
8014 currApp.lru = 0;
8015 }
8016 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008017 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008018 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8019 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8020 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8021 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8022 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8023 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8024 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8025 } else {
8026 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8027 }
8028 }
8029
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008030 private void fillInProcMemInfo(ProcessRecord app,
8031 ActivityManager.RunningAppProcessInfo outInfo) {
8032 outInfo.pid = app.pid;
8033 outInfo.uid = app.info.uid;
8034 if (mHeavyWeightProcess == app) {
8035 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8036 }
8037 if (app.persistent) {
8038 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8039 }
8040 outInfo.lastTrimLevel = app.trimMemoryLevel;
8041 int adj = app.curAdj;
8042 outInfo.importance = oomAdjToImportance(adj, outInfo);
8043 outInfo.importanceReasonCode = app.adjTypeCode;
8044 }
8045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008047 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 // Lazy instantiation of list
8049 List<ActivityManager.RunningAppProcessInfo> runList = null;
8050 synchronized (this) {
8051 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008052 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8053 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8055 // Generate process state info for running application
8056 ActivityManager.RunningAppProcessInfo currApp =
8057 new ActivityManager.RunningAppProcessInfo(app.processName,
8058 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008059 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008060 if (app.adjSource instanceof ProcessRecord) {
8061 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008062 currApp.importanceReasonImportance = oomAdjToImportance(
8063 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008064 } else if (app.adjSource instanceof ActivityRecord) {
8065 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008066 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8067 }
8068 if (app.adjTarget instanceof ComponentName) {
8069 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8070 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008071 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 // + " lru=" + currApp.lru);
8073 if (runList == null) {
8074 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8075 }
8076 runList.add(currApp);
8077 }
8078 }
8079 }
8080 return runList;
8081 }
8082
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008083 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008084 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008085 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8086 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8087 if (runningApps != null && runningApps.size() > 0) {
8088 Set<String> extList = new HashSet<String>();
8089 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8090 if (app.pkgList != null) {
8091 for (String pkg : app.pkgList) {
8092 extList.add(pkg);
8093 }
8094 }
8095 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008096 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008097 for (String pkg : extList) {
8098 try {
8099 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8100 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8101 retList.add(info);
8102 }
8103 } catch (RemoteException e) {
8104 }
8105 }
8106 }
8107 return retList;
8108 }
8109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008111 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8112 enforceNotIsolatedCaller("getMyMemoryState");
8113 synchronized (this) {
8114 ProcessRecord proc;
8115 synchronized (mPidsSelfLocked) {
8116 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8117 }
8118 fillInProcMemInfo(proc, outInfo);
8119 }
8120 }
8121
8122 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008124 if (checkCallingPermission(android.Manifest.permission.DUMP)
8125 != PackageManager.PERMISSION_GRANTED) {
8126 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8127 + Binder.getCallingPid()
8128 + ", uid=" + Binder.getCallingUid()
8129 + " without permission "
8130 + android.Manifest.permission.DUMP);
8131 return;
8132 }
8133
8134 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008135 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008136 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008137
8138 int opti = 0;
8139 while (opti < args.length) {
8140 String opt = args[opti];
8141 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8142 break;
8143 }
8144 opti++;
8145 if ("-a".equals(opt)) {
8146 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008147 } else if ("-c".equals(opt)) {
8148 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008149 } else if ("-h".equals(opt)) {
8150 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008151 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008152 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008153 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008154 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8155 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8156 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008157 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008158 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008159 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008160 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008161 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008162 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008163 pw.println(" all: dump all activities");
8164 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008165 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008166 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8167 pw.println(" a partial substring in a component name, a");
8168 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008169 pw.println(" -a: include all available server state.");
8170 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008172 } else {
8173 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008175 }
8176
8177 // Is the caller requesting to dump a particular piece of data?
8178 if (opti < args.length) {
8179 String cmd = args[opti];
8180 opti++;
8181 if ("activities".equals(cmd) || "a".equals(cmd)) {
8182 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008183 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008185 return;
8186 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008187 String[] newArgs;
8188 String name;
8189 if (opti >= args.length) {
8190 name = null;
8191 newArgs = EMPTY_STRING_ARRAY;
8192 } else {
8193 name = args[opti];
8194 opti++;
8195 newArgs = new String[args.length - opti];
8196 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8197 args.length - opti);
8198 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008199 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008200 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008201 }
8202 return;
8203 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008204 String[] newArgs;
8205 String name;
8206 if (opti >= args.length) {
8207 name = null;
8208 newArgs = EMPTY_STRING_ARRAY;
8209 } else {
8210 name = args[opti];
8211 opti++;
8212 newArgs = new String[args.length - opti];
8213 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8214 args.length - opti);
8215 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008216 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008217 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008218 }
8219 return;
8220 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008221 String[] newArgs;
8222 String name;
8223 if (opti >= args.length) {
8224 name = null;
8225 newArgs = EMPTY_STRING_ARRAY;
8226 } else {
8227 name = args[opti];
8228 opti++;
8229 newArgs = new String[args.length - opti];
8230 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8231 args.length - opti);
8232 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008233 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008234 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008235 }
8236 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008237 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8238 synchronized (this) {
8239 dumpOomLocked(fd, pw, args, opti, true);
8240 }
8241 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008242 } else if ("provider".equals(cmd)) {
8243 String[] newArgs;
8244 String name;
8245 if (opti >= args.length) {
8246 name = null;
8247 newArgs = EMPTY_STRING_ARRAY;
8248 } else {
8249 name = args[opti];
8250 opti++;
8251 newArgs = new String[args.length - opti];
8252 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8253 }
8254 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8255 pw.println("No providers match: " + name);
8256 pw.println("Use -h for help.");
8257 }
8258 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008259 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8260 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008261 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008262 }
8263 return;
8264 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008265 String[] newArgs;
8266 String name;
8267 if (opti >= args.length) {
8268 name = null;
8269 newArgs = EMPTY_STRING_ARRAY;
8270 } else {
8271 name = args[opti];
8272 opti++;
8273 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008274 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8275 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008276 }
8277 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8278 pw.println("No services match: " + name);
8279 pw.println("Use -h for help.");
8280 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008281 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008282 } else if ("package".equals(cmd)) {
8283 String[] newArgs;
8284 if (opti >= args.length) {
8285 pw.println("package: no package name specified");
8286 pw.println("Use -h for help.");
8287 return;
8288 } else {
8289 dumpPackage = args[opti];
8290 opti++;
8291 newArgs = new String[args.length - opti];
8292 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8293 args.length - opti);
8294 args = newArgs;
8295 opti = 0;
8296 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008297 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8298 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008299 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008300 }
8301 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008302 } else {
8303 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008304 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8305 pw.println("Bad activity command, or no activities match: " + cmd);
8306 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008307 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008308 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008310 }
8311
8312 // No piece of data specified, dump everything.
8313 synchronized (this) {
8314 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008315 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008316 if (needSep) {
8317 pw.println(" ");
8318 }
8319 if (dumpAll) {
8320 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008321 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008323 if (needSep) {
8324 pw.println(" ");
8325 }
8326 if (dumpAll) {
8327 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008328 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008329 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008330 if (needSep) {
8331 pw.println(" ");
8332 }
8333 if (dumpAll) {
8334 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008335 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008336 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008337 if (needSep) {
8338 pw.println(" ");
8339 }
8340 if (dumpAll) {
8341 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008342 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008343 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008344 if (needSep) {
8345 pw.println(" ");
8346 }
8347 if (dumpAll) {
8348 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008349 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008350 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 }
8352 }
8353
8354 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008355 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008356 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8357 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008358 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8359 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008360 pw.println(" ");
8361 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008362 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8363 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008364 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008365 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008366 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008367 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008368 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008369 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008370 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008372 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008373 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008374 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008375 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008376 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8377 pw.println(" ");
8378 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008379 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008380 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008381 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008382 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008383 pw.println(" ");
8384 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008385 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008386 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008389 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008390 if (mMainStack.mPausingActivity != null) {
8391 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008392 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008393 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008394 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008395 if (dumpAll) {
8396 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8397 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008398 pw.println(" mDismissKeyguardOnNextActivity: "
8399 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008401
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008402 if (mRecentTasks.size() > 0) {
8403 pw.println();
8404 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008405
8406 final int N = mRecentTasks.size();
8407 for (int i=0; i<N; i++) {
8408 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008409 if (dumpPackage != null) {
8410 if (tr.realActivity == null ||
8411 !dumpPackage.equals(tr.realActivity)) {
8412 continue;
8413 }
8414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8416 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008417 if (dumpAll) {
8418 mRecentTasks.get(i).dump(pw, " ");
8419 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008420 }
8421 }
8422
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008423 if (dumpAll) {
8424 pw.println(" ");
8425 pw.println(" mCurTask: " + mCurTask);
8426 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008427
8428 return true;
8429 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008430
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008431 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008432 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008433 boolean needSep = false;
8434 int numPers = 0;
8435
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008436 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8437
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008438 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008439 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8440 final int NA = procs.size();
8441 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008442 ProcessRecord r = procs.valueAt(ia);
8443 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8444 continue;
8445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446 if (!needSep) {
8447 pw.println(" All known processes:");
8448 needSep = true;
8449 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008450 pw.print(r.persistent ? " *PERS*" : " *APP*");
8451 pw.print(" UID "); pw.print(procs.keyAt(ia));
8452 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 r.dump(pw, " ");
8454 if (r.persistent) {
8455 numPers++;
8456 }
8457 }
8458 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008459 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008460
8461 if (mIsolatedProcesses.size() > 0) {
8462 if (needSep) pw.println(" ");
8463 needSep = true;
8464 pw.println(" Isolated process list (sorted by uid):");
8465 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8466 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8467 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8468 continue;
8469 }
8470 pw.println(String.format("%sIsolated #%2d: %s",
8471 " ", i, r.toString()));
8472 }
8473 }
8474
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008475 if (mLruProcesses.size() > 0) {
8476 if (needSep) pw.println(" ");
8477 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008478 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008479 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008480 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008481 needSep = true;
8482 }
8483
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008484 if (dumpAll) {
8485 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008486 boolean printed = false;
8487 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8488 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8489 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8490 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008491 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008492 if (!printed) {
8493 if (needSep) pw.println(" ");
8494 needSep = true;
8495 pw.println(" PID mappings:");
8496 printed = true;
8497 }
8498 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8499 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 }
8501 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008502 }
8503
8504 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008505 synchronized (mPidsSelfLocked) {
8506 boolean printed = false;
8507 for (int i=0; i<mForegroundProcesses.size(); i++) {
8508 ProcessRecord r = mPidsSelfLocked.get(
8509 mForegroundProcesses.valueAt(i).pid);
8510 if (dumpPackage != null && (r == null
8511 || !dumpPackage.equals(r.info.packageName))) {
8512 continue;
8513 }
8514 if (!printed) {
8515 if (needSep) pw.println(" ");
8516 needSep = true;
8517 pw.println(" Foreground Processes:");
8518 printed = true;
8519 }
8520 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8521 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008524 }
8525
8526 if (mPersistentStartingProcesses.size() > 0) {
8527 if (needSep) pw.println(" ");
8528 needSep = true;
8529 pw.println(" Persisent processes that are starting:");
8530 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008531 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 if (mRemovedProcesses.size() > 0) {
8535 if (needSep) pw.println(" ");
8536 needSep = true;
8537 pw.println(" Processes that are being removed:");
8538 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008539 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008540 }
8541
8542 if (mProcessesOnHold.size() > 0) {
8543 if (needSep) pw.println(" ");
8544 needSep = true;
8545 pw.println(" Processes that are on old until the system is ready:");
8546 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008547 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008550 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551
8552 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008553 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 long now = SystemClock.uptimeMillis();
8555 for (Map.Entry<String, SparseArray<Long>> procs
8556 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008557 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008558 SparseArray<Long> uids = procs.getValue();
8559 final int N = uids.size();
8560 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008561 int puid = uids.keyAt(i);
8562 ProcessRecord r = mProcessNames.get(pname, puid);
8563 if (dumpPackage != null && (r == null
8564 || !dumpPackage.equals(r.info.packageName))) {
8565 continue;
8566 }
8567 if (!printed) {
8568 if (needSep) pw.println(" ");
8569 needSep = true;
8570 pw.println(" Time since processes crashed:");
8571 printed = true;
8572 }
8573 pw.print(" Process "); pw.print(pname);
8574 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008575 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008576 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8577 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008578 }
8579 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008582 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008583 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008584 for (Map.Entry<String, SparseArray<Long>> procs
8585 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008586 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008587 SparseArray<Long> uids = procs.getValue();
8588 final int N = uids.size();
8589 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008590 int puid = uids.keyAt(i);
8591 ProcessRecord r = mProcessNames.get(pname, puid);
8592 if (dumpPackage != null && (r == null
8593 || !dumpPackage.equals(r.info.packageName))) {
8594 continue;
8595 }
8596 if (!printed) {
8597 if (needSep) pw.println(" ");
8598 needSep = true;
8599 pw.println(" Bad processes:");
8600 }
8601 pw.print(" Bad process "); pw.print(pname);
8602 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008603 pw.print(": crashed at time ");
8604 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 }
8606 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008608
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008609 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008610 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008611 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008612 if (dumpAll) {
8613 StringBuilder sb = new StringBuilder(128);
8614 sb.append(" mPreviousProcessVisibleTime: ");
8615 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8616 pw.println(sb);
8617 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008618 if (mHeavyWeightProcess != null) {
8619 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8620 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008621 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008622 if (dumpAll) {
8623 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008624 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008625 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008626 for (Map.Entry<String, Integer> entry
8627 : mCompatModePackages.getPackages().entrySet()) {
8628 String pkg = entry.getKey();
8629 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008630 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8631 continue;
8632 }
8633 if (!printed) {
8634 pw.println(" mScreenCompatPackages:");
8635 printed = true;
8636 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008637 pw.print(" "); pw.print(pkg); pw.print(": ");
8638 pw.print(mode); pw.println();
8639 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008640 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008641 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008642 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8643 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8644 || mOrigWaitForDebugger) {
8645 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8646 + " mDebugTransient=" + mDebugTransient
8647 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8648 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008649 if (mOpenGlTraceApp != null) {
8650 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8651 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008652 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8653 || mProfileFd != null) {
8654 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8655 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8656 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8657 + mAutoStopProfiler);
8658 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 if (mAlwaysFinishActivities || mController != null) {
8660 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8661 + " mController=" + mController);
8662 }
8663 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008665 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008666 + " mProcessesReady=" + mProcessesReady
8667 + " mSystemReady=" + mSystemReady);
8668 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 + " mBooted=" + mBooted
8670 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008671 pw.print(" mLastPowerCheckRealtime=");
8672 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8673 pw.println("");
8674 pw.print(" mLastPowerCheckUptime=");
8675 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8676 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008677 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8678 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008679 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008680 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8681 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008682 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008683
8684 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008685 }
8686
Dianne Hackborn287952c2010-09-22 22:34:31 -07008687 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008688 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008689 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008690 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008691 long now = SystemClock.uptimeMillis();
8692 for (int i=0; i<mProcessesToGc.size(); i++) {
8693 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008694 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8695 continue;
8696 }
8697 if (!printed) {
8698 if (needSep) pw.println(" ");
8699 needSep = true;
8700 pw.println(" Processes that are waiting to GC:");
8701 printed = true;
8702 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008703 pw.print(" Process "); pw.println(proc);
8704 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8705 pw.print(", last gced=");
8706 pw.print(now-proc.lastRequestedGc);
8707 pw.print(" ms ago, last lowMem=");
8708 pw.print(now-proc.lastLowMemory);
8709 pw.println(" ms ago");
8710
8711 }
8712 }
8713 return needSep;
8714 }
8715
8716 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8717 int opti, boolean dumpAll) {
8718 boolean needSep = false;
8719
8720 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008721 if (needSep) pw.println(" ");
8722 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008723 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008724 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008725 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008726 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8727 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8728 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8729 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8730 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008731 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008732 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008733 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008734 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008735 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008736 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008737
8738 if (needSep) pw.println(" ");
8739 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008740 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008741 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008742 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008743 needSep = true;
8744 }
8745
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008746 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008747
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008748 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008749 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008750 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008751 if (mHeavyWeightProcess != null) {
8752 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8753 }
8754
8755 return true;
8756 }
8757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008758 /**
8759 * There are three ways to call this:
8760 * - no service specified: dump all the services
8761 * - a flattened component name that matched an existing service was specified as the
8762 * first arg: dump that one service
8763 * - the first arg isn't the flattened component name of an existing service:
8764 * dump all services whose component contains the first arg as a substring
8765 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008766 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8767 int opti, boolean dumpAll) {
8768 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008770 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008771 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008772 try {
8773 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8774 for (UserInfo user : users) {
8775 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8776 services.add(r1);
8777 }
8778 }
8779 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008780 }
8781 }
8782 } else {
8783 ComponentName componentName = name != null
8784 ? ComponentName.unflattenFromString(name) : null;
8785 int objectId = 0;
8786 if (componentName == null) {
8787 // Not a '/' separated full component name; maybe an object ID?
8788 try {
8789 objectId = Integer.parseInt(name, 16);
8790 name = null;
8791 componentName = null;
8792 } catch (RuntimeException e) {
8793 }
8794 }
8795
8796 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008797 try {
8798 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8799 for (UserInfo user : users) {
8800 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8801 if (componentName != null) {
8802 if (r1.name.equals(componentName)) {
8803 services.add(r1);
8804 }
8805 } else if (name != null) {
8806 if (r1.name.flattenToString().contains(name)) {
8807 services.add(r1);
8808 }
8809 } else if (System.identityHashCode(r1) == objectId) {
8810 services.add(r1);
8811 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008812 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008813 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008814 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 }
8816 }
8817 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008818
8819 if (services.size() <= 0) {
8820 return false;
8821 }
8822
8823 boolean needSep = false;
8824 for (int i=0; i<services.size(); i++) {
8825 if (needSep) {
8826 pw.println();
8827 }
8828 needSep = true;
8829 dumpService("", fd, pw, services.get(i), args, dumpAll);
8830 }
8831 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 }
8833
8834 /**
8835 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8836 * there is a thread associated with the service.
8837 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008838 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8839 final ServiceRecord r, String[] args, boolean dumpAll) {
8840 String innerPrefix = prefix + " ";
8841 synchronized (this) {
8842 pw.print(prefix); pw.print("SERVICE ");
8843 pw.print(r.shortName); pw.print(" ");
8844 pw.print(Integer.toHexString(System.identityHashCode(r)));
8845 pw.print(" pid=");
8846 if (r.app != null) pw.println(r.app.pid);
8847 else pw.println("(not running)");
8848 if (dumpAll) {
8849 r.dump(pw, innerPrefix);
8850 }
8851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008853 pw.print(prefix); pw.println(" Client:");
8854 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008856 TransferPipe tp = new TransferPipe();
8857 try {
8858 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8859 tp.setBufferPrefix(prefix + " ");
8860 tp.go(fd);
8861 } finally {
8862 tp.kill();
8863 }
8864 } catch (IOException e) {
8865 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008867 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 }
8869 }
8870 }
8871
Marco Nelissen18cb2872011-11-15 11:19:53 -08008872 /**
8873 * There are three ways to call this:
8874 * - no provider specified: dump all the providers
8875 * - a flattened component name that matched an existing provider was specified as the
8876 * first arg: dump that one provider
8877 * - the first arg isn't the flattened component name of an existing provider:
8878 * dump all providers whose component contains the first arg as a substring
8879 */
8880 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8881 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008882 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008883 }
8884
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008885 static class ItemMatcher {
8886 ArrayList<ComponentName> components;
8887 ArrayList<String> strings;
8888 ArrayList<Integer> objects;
8889 boolean all;
8890
8891 ItemMatcher() {
8892 all = true;
8893 }
8894
8895 void build(String name) {
8896 ComponentName componentName = ComponentName.unflattenFromString(name);
8897 if (componentName != null) {
8898 if (components == null) {
8899 components = new ArrayList<ComponentName>();
8900 }
8901 components.add(componentName);
8902 all = false;
8903 } else {
8904 int objectId = 0;
8905 // Not a '/' separated full component name; maybe an object ID?
8906 try {
8907 objectId = Integer.parseInt(name, 16);
8908 if (objects == null) {
8909 objects = new ArrayList<Integer>();
8910 }
8911 objects.add(objectId);
8912 all = false;
8913 } catch (RuntimeException e) {
8914 // Not an integer; just do string match.
8915 if (strings == null) {
8916 strings = new ArrayList<String>();
8917 }
8918 strings.add(name);
8919 all = false;
8920 }
8921 }
8922 }
8923
8924 int build(String[] args, int opti) {
8925 for (; opti<args.length; opti++) {
8926 String name = args[opti];
8927 if ("--".equals(name)) {
8928 return opti+1;
8929 }
8930 build(name);
8931 }
8932 return opti;
8933 }
8934
8935 boolean match(Object object, ComponentName comp) {
8936 if (all) {
8937 return true;
8938 }
8939 if (components != null) {
8940 for (int i=0; i<components.size(); i++) {
8941 if (components.get(i).equals(comp)) {
8942 return true;
8943 }
8944 }
8945 }
8946 if (objects != null) {
8947 for (int i=0; i<objects.size(); i++) {
8948 if (System.identityHashCode(object) == objects.get(i)) {
8949 return true;
8950 }
8951 }
8952 }
8953 if (strings != null) {
8954 String flat = comp.flattenToString();
8955 for (int i=0; i<strings.size(); i++) {
8956 if (flat.contains(strings.get(i))) {
8957 return true;
8958 }
8959 }
8960 }
8961 return false;
8962 }
8963 }
8964
Dianne Hackborn625ac272010-09-17 18:29:22 -07008965 /**
8966 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008967 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008968 * - the cmd arg isn't the flattened component name of an existing activity:
8969 * dump all activity whose component contains the cmd as a substring
8970 * - A hex number of the ActivityRecord object instance.
8971 */
8972 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8973 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008974 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008975
8976 if ("all".equals(name)) {
8977 synchronized (this) {
8978 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008979 activities.add(r1);
8980 }
8981 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008982 } else if ("top".equals(name)) {
8983 synchronized (this) {
8984 final int N = mMainStack.mHistory.size();
8985 if (N > 0) {
8986 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8987 }
8988 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008989 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008990 ItemMatcher matcher = new ItemMatcher();
8991 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008992
8993 synchronized (this) {
8994 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008995 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008996 activities.add(r1);
8997 }
8998 }
8999 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009000 }
9001
9002 if (activities.size() <= 0) {
9003 return false;
9004 }
9005
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009006 String[] newArgs = new String[args.length - opti];
9007 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9008
Dianne Hackborn30d71892010-12-11 10:37:55 -08009009 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009010 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009011 for (int i=activities.size()-1; i>=0; i--) {
9012 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009013 if (needSep) {
9014 pw.println();
9015 }
9016 needSep = true;
9017 synchronized (this) {
9018 if (lastTask != r.task) {
9019 lastTask = r.task;
9020 pw.print("TASK "); pw.print(lastTask.affinity);
9021 pw.print(" id="); pw.println(lastTask.taskId);
9022 if (dumpAll) {
9023 lastTask.dump(pw, " ");
9024 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009025 }
9026 }
9027 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009028 }
9029 return true;
9030 }
9031
9032 /**
9033 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9034 * there is a thread associated with the activity.
9035 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009036 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009037 final ActivityRecord r, String[] args, boolean dumpAll) {
9038 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009039 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009040 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9041 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9042 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009043 if (r.app != null) pw.println(r.app.pid);
9044 else pw.println("(not running)");
9045 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009046 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009047 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009048 }
9049 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009050 // flush anything that is already in the PrintWriter since the thread is going
9051 // to write to the file descriptor directly
9052 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009053 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009054 TransferPipe tp = new TransferPipe();
9055 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009056 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9057 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009058 tp.go(fd);
9059 } finally {
9060 tp.kill();
9061 }
9062 } catch (IOException e) {
9063 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009064 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009065 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009066 }
9067 }
9068 }
9069
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009070 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009071 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009072 boolean needSep = false;
9073
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009074 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009075 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009077 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 Iterator it = mRegisteredReceivers.values().iterator();
9079 while (it.hasNext()) {
9080 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009081 if (dumpPackage != null && (r.app == null ||
9082 !dumpPackage.equals(r.app.info.packageName))) {
9083 continue;
9084 }
9085 if (!printed) {
9086 pw.println(" Registered Receivers:");
9087 needSep = true;
9088 printed = true;
9089 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009090 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 r.dump(pw, " ");
9092 }
9093 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009094
9095 if (mReceiverResolver.dump(pw, needSep ?
9096 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9097 " ", dumpPackage, false)) {
9098 needSep = true;
9099 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009100 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009101
9102 for (BroadcastQueue q : mBroadcastQueues) {
9103 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009105
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009106 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009107
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009108 if (mStickyBroadcasts != null && dumpPackage == null) {
9109 if (needSep) {
9110 pw.println();
9111 }
9112 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009113 pw.println(" Sticky broadcasts:");
9114 StringBuilder sb = new StringBuilder(128);
9115 for (Map.Entry<String, ArrayList<Intent>> ent
9116 : mStickyBroadcasts.entrySet()) {
9117 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009118 if (dumpAll) {
9119 pw.println(":");
9120 ArrayList<Intent> intents = ent.getValue();
9121 final int N = intents.size();
9122 for (int i=0; i<N; i++) {
9123 sb.setLength(0);
9124 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009125 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009126 pw.println(sb.toString());
9127 Bundle bundle = intents.get(i).getExtras();
9128 if (bundle != null) {
9129 pw.print(" ");
9130 pw.println(bundle.toString());
9131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009133 } else {
9134 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009135 }
9136 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009137 needSep = true;
9138 }
9139
9140 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009141 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009142 for (BroadcastQueue queue : mBroadcastQueues) {
9143 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9144 + queue.mBroadcastsScheduled);
9145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 pw.println(" mHandler:");
9147 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009148 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009150
9151 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009152 }
9153
Marco Nelissen18cb2872011-11-15 11:19:53 -08009154 /**
9155 * Prints a list of ServiceRecords (dumpsys activity services)
9156 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009157 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009158 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009159 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009160
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009161 ItemMatcher matcher = new ItemMatcher();
9162 matcher.build(args, opti);
9163
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009164 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009165 try {
9166 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9167 for (UserInfo user : users) {
9168 if (mServiceMap.getAllServices(user.id).size() > 0) {
9169 boolean printed = false;
9170 long nowReal = SystemClock.elapsedRealtime();
9171 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9172 user.id).iterator();
9173 needSep = false;
9174 while (it.hasNext()) {
9175 ServiceRecord r = it.next();
9176 if (!matcher.match(r, r.name)) {
9177 continue;
9178 }
9179 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9180 continue;
9181 }
9182 if (!printed) {
9183 pw.println(" Active services:");
9184 printed = true;
9185 }
9186 if (needSep) {
9187 pw.println();
9188 }
9189 pw.print(" * ");
9190 pw.println(r);
9191 if (dumpAll) {
9192 r.dump(pw, " ");
9193 needSep = true;
9194 } else {
9195 pw.print(" app=");
9196 pw.println(r.app);
9197 pw.print(" created=");
9198 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9199 pw.print(" started=");
9200 pw.print(r.startRequested);
9201 pw.print(" connections=");
9202 pw.println(r.connections.size());
9203 if (r.connections.size() > 0) {
9204 pw.println(" Connections:");
9205 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9206 for (int i = 0; i < clist.size(); i++) {
9207 ConnectionRecord conn = clist.get(i);
9208 pw.print(" ");
9209 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009210 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009211 pw.print(" -> ");
9212 ProcessRecord proc = conn.binding.client;
9213 pw.println(proc != null ? proc.toShortString() : "null");
9214 }
9215 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009216 }
9217 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009218 if (dumpClient && r.app != null && r.app.thread != null) {
9219 pw.println(" Client:");
9220 pw.flush();
9221 try {
9222 TransferPipe tp = new TransferPipe();
9223 try {
9224 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9225 r, args);
9226 tp.setBufferPrefix(" ");
9227 // Short timeout, since blocking here can
9228 // deadlock with the application.
9229 tp.go(fd, 2000);
9230 } finally {
9231 tp.kill();
9232 }
9233 } catch (IOException e) {
9234 pw.println(" Failure while dumping the service: " + e);
9235 } catch (RemoteException e) {
9236 pw.println(" Got a RemoteException while dumping the service");
9237 }
9238 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009240 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009241 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009244 } catch (RemoteException re) {
9245
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009249 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009250 for (int i=0; i<mPendingServices.size(); i++) {
9251 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009252 if (!matcher.match(r, r.name)) {
9253 continue;
9254 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009255 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9256 continue;
9257 }
9258 if (!printed) {
9259 if (needSep) pw.println(" ");
9260 needSep = true;
9261 pw.println(" Pending services:");
9262 printed = true;
9263 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 pw.print(" * Pending "); pw.println(r);
9265 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009267 needSep = true;
9268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009271 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272 for (int i=0; i<mRestartingServices.size(); i++) {
9273 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009274 if (!matcher.match(r, r.name)) {
9275 continue;
9276 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009277 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9278 continue;
9279 }
9280 if (!printed) {
9281 if (needSep) pw.println(" ");
9282 needSep = true;
9283 pw.println(" Restarting services:");
9284 printed = true;
9285 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009286 pw.print(" * Restarting "); pw.println(r);
9287 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009289 needSep = true;
9290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009291
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009292 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009293 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009294 for (int i=0; i<mStoppingServices.size(); i++) {
9295 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009296 if (!matcher.match(r, r.name)) {
9297 continue;
9298 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009299 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9300 continue;
9301 }
9302 if (!printed) {
9303 if (needSep) pw.println(" ");
9304 needSep = true;
9305 pw.println(" Stopping services:");
9306 printed = true;
9307 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009308 pw.print(" * Stopping "); pw.println(r);
9309 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009310 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 needSep = true;
9312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009314 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009316 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009317 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 = mServiceConnections.values().iterator();
9319 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009320 ArrayList<ConnectionRecord> r = it.next();
9321 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009322 ConnectionRecord cr = r.get(i);
9323 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9324 continue;
9325 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009326 if (dumpPackage != null && (cr.binding.client == null
9327 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9328 continue;
9329 }
9330 if (!printed) {
9331 if (needSep) pw.println(" ");
9332 needSep = true;
9333 pw.println(" Connection bindings to services:");
9334 printed = true;
9335 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009336 pw.print(" * "); pw.println(cr);
9337 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009340 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341 }
9342 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009343
9344 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009345 }
9346
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009347 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009348 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009349 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009351 ItemMatcher matcher = new ItemMatcher();
9352 matcher.build(args, opti);
9353
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009354 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009355
9356 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357
9358 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009359 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009360 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009361 ContentProviderRecord r = mLaunchingProviders.get(i);
9362 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9363 continue;
9364 }
9365 if (!printed) {
9366 if (needSep) pw.println(" ");
9367 needSep = true;
9368 pw.println(" Launching content providers:");
9369 printed = true;
9370 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009371 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009372 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009373 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009374 }
9375
9376 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009377 if (needSep) pw.println();
9378 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009379 pw.println("Granted Uri Permissions:");
9380 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9381 int uid = mGrantedUriPermissions.keyAt(i);
9382 HashMap<Uri, UriPermission> perms
9383 = mGrantedUriPermissions.valueAt(i);
9384 pw.print(" * UID "); pw.print(uid);
9385 pw.println(" holds:");
9386 for (UriPermission perm : perms.values()) {
9387 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009388 if (dumpAll) {
9389 perm.dump(pw, " ");
9390 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009391 }
9392 }
9393 needSep = true;
9394 }
9395
9396 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009397 }
9398
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009399 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009400 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009401 boolean needSep = false;
9402
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009403 if (mIntentSenderRecords.size() > 0) {
9404 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009405 Iterator<WeakReference<PendingIntentRecord>> it
9406 = mIntentSenderRecords.values().iterator();
9407 while (it.hasNext()) {
9408 WeakReference<PendingIntentRecord> ref = it.next();
9409 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009410 if (dumpPackage != null && (rec == null
9411 || !dumpPackage.equals(rec.key.packageName))) {
9412 continue;
9413 }
9414 if (!printed) {
9415 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9416 printed = true;
9417 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009418 needSep = true;
9419 if (rec != null) {
9420 pw.print(" * "); pw.println(rec);
9421 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009424 } else {
9425 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009426 }
9427 }
9428 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009429
9430 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 }
9432
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009433 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009434 String prefix, String label, boolean complete, boolean brief, boolean client,
9435 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009437 boolean needNL = false;
9438 final String innerPrefix = prefix + " ";
9439 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009440 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009441 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009442 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9443 continue;
9444 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009445 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009446 if (needNL) {
9447 pw.println(" ");
9448 needNL = false;
9449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 if (lastTask != r.task) {
9451 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009452 pw.print(prefix);
9453 pw.print(full ? "* " : " ");
9454 pw.println(lastTask);
9455 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009456 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009457 } else if (complete) {
9458 // Complete + brief == give a summary. Isn't that obvious?!?
9459 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009460 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009461 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009462 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009465 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9466 pw.print(" #"); pw.print(i); pw.print(": ");
9467 pw.println(r);
9468 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009469 r.dump(pw, innerPrefix);
9470 } else if (complete) {
9471 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009472 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009473 if (r.app != null) {
9474 pw.print(innerPrefix); pw.println(r.app);
9475 }
9476 }
9477 if (client && r.app != null && r.app.thread != null) {
9478 // flush anything that is already in the PrintWriter since the thread is going
9479 // to write to the file descriptor directly
9480 pw.flush();
9481 try {
9482 TransferPipe tp = new TransferPipe();
9483 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009484 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9485 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009486 // Short timeout, since blocking here can
9487 // deadlock with the application.
9488 tp.go(fd, 2000);
9489 } finally {
9490 tp.kill();
9491 }
9492 } catch (IOException e) {
9493 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9494 } catch (RemoteException e) {
9495 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9496 }
9497 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009499 }
9500 }
9501
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009502 private static String buildOomTag(String prefix, String space, int val, int base) {
9503 if (val == base) {
9504 if (space == null) return prefix;
9505 return prefix + " ";
9506 }
9507 return prefix + "+" + Integer.toString(val-base);
9508 }
9509
9510 private static final int dumpProcessList(PrintWriter pw,
9511 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009512 String prefix, String normalLabel, String persistentLabel,
9513 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009514 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009515 final int N = list.size()-1;
9516 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009518 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9519 continue;
9520 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009521 pw.println(String.format("%s%s #%2d: %s",
9522 prefix, (r.persistent ? persistentLabel : normalLabel),
9523 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524 if (r.persistent) {
9525 numPers++;
9526 }
9527 }
9528 return numPers;
9529 }
9530
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009531 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009532 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009533 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009534 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009535
Dianne Hackborn905577f2011-09-07 18:31:28 -07009536 ArrayList<Pair<ProcessRecord, Integer>> list
9537 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9538 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009539 ProcessRecord r = origList.get(i);
9540 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9541 continue;
9542 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009543 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9544 }
9545
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009546 if (list.size() <= 0) {
9547 return false;
9548 }
9549
Dianne Hackborn905577f2011-09-07 18:31:28 -07009550 Comparator<Pair<ProcessRecord, Integer>> comparator
9551 = new Comparator<Pair<ProcessRecord, Integer>>() {
9552 @Override
9553 public int compare(Pair<ProcessRecord, Integer> object1,
9554 Pair<ProcessRecord, Integer> object2) {
9555 if (object1.first.setAdj != object2.first.setAdj) {
9556 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9557 }
9558 if (object1.second.intValue() != object2.second.intValue()) {
9559 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9560 }
9561 return 0;
9562 }
9563 };
9564
9565 Collections.sort(list, comparator);
9566
Dianne Hackborn287952c2010-09-22 22:34:31 -07009567 final long curRealtime = SystemClock.elapsedRealtime();
9568 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9569 final long curUptime = SystemClock.uptimeMillis();
9570 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9571
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009572 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009573 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009574 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009575 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009576 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009577 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9578 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009579 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9580 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009581 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9582 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009583 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9584 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009585 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009586 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009587 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9588 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9589 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9590 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9591 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9592 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9593 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9594 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009595 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9596 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009597 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9598 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009599 } else {
9600 oomAdj = Integer.toString(r.setAdj);
9601 }
9602 String schedGroup;
9603 switch (r.setSchedGroup) {
9604 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9605 schedGroup = "B";
9606 break;
9607 case Process.THREAD_GROUP_DEFAULT:
9608 schedGroup = "F";
9609 break;
9610 default:
9611 schedGroup = Integer.toString(r.setSchedGroup);
9612 break;
9613 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009614 String foreground;
9615 if (r.foregroundActivities) {
9616 foreground = "A";
9617 } else if (r.foregroundServices) {
9618 foreground = "S";
9619 } else {
9620 foreground = " ";
9621 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009622 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009623 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009624 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9625 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009626 if (r.adjSource != null || r.adjTarget != null) {
9627 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009628 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009629 if (r.adjTarget instanceof ComponentName) {
9630 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9631 } else if (r.adjTarget != null) {
9632 pw.print(r.adjTarget.toString());
9633 } else {
9634 pw.print("{null}");
9635 }
9636 pw.print("<=");
9637 if (r.adjSource instanceof ProcessRecord) {
9638 pw.print("Proc{");
9639 pw.print(((ProcessRecord)r.adjSource).toShortString());
9640 pw.println("}");
9641 } else if (r.adjSource != null) {
9642 pw.println(r.adjSource.toString());
9643 } else {
9644 pw.println("{null}");
9645 }
9646 }
9647 if (inclDetails) {
9648 pw.print(prefix);
9649 pw.print(" ");
9650 pw.print("oom: max="); pw.print(r.maxAdj);
9651 pw.print(" hidden="); pw.print(r.hiddenAdj);
9652 pw.print(" curRaw="); pw.print(r.curRawAdj);
9653 pw.print(" setRaw="); pw.print(r.setRawAdj);
9654 pw.print(" cur="); pw.print(r.curAdj);
9655 pw.print(" set="); pw.println(r.setAdj);
9656 pw.print(prefix);
9657 pw.print(" ");
9658 pw.print("keeping="); pw.print(r.keeping);
9659 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009660 pw.print(" empty="); pw.print(r.empty);
9661 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009662
9663 if (!r.keeping) {
9664 if (r.lastWakeTime != 0) {
9665 long wtime;
9666 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9667 synchronized (stats) {
9668 wtime = stats.getProcessWakeTime(r.info.uid,
9669 r.pid, curRealtime);
9670 }
9671 long timeUsed = wtime - r.lastWakeTime;
9672 pw.print(prefix);
9673 pw.print(" ");
9674 pw.print("keep awake over ");
9675 TimeUtils.formatDuration(realtimeSince, pw);
9676 pw.print(" used ");
9677 TimeUtils.formatDuration(timeUsed, pw);
9678 pw.print(" (");
9679 pw.print((timeUsed*100)/realtimeSince);
9680 pw.println("%)");
9681 }
9682 if (r.lastCpuTime != 0) {
9683 long timeUsed = r.curCpuTime - r.lastCpuTime;
9684 pw.print(prefix);
9685 pw.print(" ");
9686 pw.print("run cpu over ");
9687 TimeUtils.formatDuration(uptimeSince, pw);
9688 pw.print(" used ");
9689 TimeUtils.formatDuration(timeUsed, pw);
9690 pw.print(" (");
9691 pw.print((timeUsed*100)/uptimeSince);
9692 pw.println("%)");
9693 }
9694 }
9695 }
9696 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009697 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009698 }
9699
Dianne Hackbornb437e092011-08-05 17:50:29 -07009700 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009701 ArrayList<ProcessRecord> procs;
9702 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009703 if (args != null && args.length > start
9704 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009705 procs = new ArrayList<ProcessRecord>();
9706 int pid = -1;
9707 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009708 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009709 } catch (NumberFormatException e) {
9710
9711 }
9712 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9713 ProcessRecord proc = mLruProcesses.get(i);
9714 if (proc.pid == pid) {
9715 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009716 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009717 procs.add(proc);
9718 }
9719 }
9720 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009721 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009722 return null;
9723 }
9724 } else {
9725 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9726 }
9727 }
9728 return procs;
9729 }
9730
9731 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9732 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009733 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009734 if (procs == null) {
9735 return;
9736 }
9737
9738 long uptime = SystemClock.uptimeMillis();
9739 long realtime = SystemClock.elapsedRealtime();
9740 pw.println("Applications Graphics Acceleration Info:");
9741 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9742
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009743 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9744 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009745 if (r.thread != null) {
9746 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9747 pw.flush();
9748 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009749 TransferPipe tp = new TransferPipe();
9750 try {
9751 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9752 tp.go(fd);
9753 } finally {
9754 tp.kill();
9755 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009756 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009757 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009758 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009759 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009760 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009761 pw.flush();
9762 }
9763 }
9764 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009765 }
9766
Jeff Brown6754ba22011-12-14 20:20:01 -08009767 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9768 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9769 if (procs == null) {
9770 return;
9771 }
9772
9773 pw.println("Applications Database Info:");
9774
9775 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9776 ProcessRecord r = procs.get(i);
9777 if (r.thread != null) {
9778 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9779 pw.flush();
9780 try {
9781 TransferPipe tp = new TransferPipe();
9782 try {
9783 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9784 tp.go(fd);
9785 } finally {
9786 tp.kill();
9787 }
9788 } catch (IOException e) {
9789 pw.println("Failure while dumping the app: " + r);
9790 pw.flush();
9791 } catch (RemoteException e) {
9792 pw.println("Got a RemoteException while dumping the app " + r);
9793 pw.flush();
9794 }
9795 }
9796 }
9797 }
9798
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009799 final static class MemItem {
9800 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009801 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009802 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009803 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009804 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009805
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009806 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009807 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009808 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009809 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009810 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009811 }
9812 }
9813
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009814 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009815 boolean sort) {
9816 if (sort) {
9817 Collections.sort(items, new Comparator<MemItem>() {
9818 @Override
9819 public int compare(MemItem lhs, MemItem rhs) {
9820 if (lhs.pss < rhs.pss) {
9821 return 1;
9822 } else if (lhs.pss > rhs.pss) {
9823 return -1;
9824 }
9825 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009826 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009827 });
9828 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009829
9830 for (int i=0; i<items.size(); i++) {
9831 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009832 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009833 if (mi.subitems != null) {
9834 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9835 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009836 }
9837 }
9838
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009839 // These are in KB.
9840 static final long[] DUMP_MEM_BUCKETS = new long[] {
9841 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9842 120*1024, 160*1024, 200*1024,
9843 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9844 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9845 };
9846
Dianne Hackborn672342c2011-11-29 11:29:02 -08009847 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9848 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009849 int start = label.lastIndexOf('.');
9850 if (start >= 0) start++;
9851 else start = 0;
9852 int end = label.length();
9853 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9854 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9855 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9856 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009857 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009858 out.append(label, start, end);
9859 return;
9860 }
9861 }
9862 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009863 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009864 out.append(label, start, end);
9865 }
9866
9867 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9868 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9869 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9870 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9871 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9872 };
9873 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9874 "System", "Persistent", "Foreground",
9875 "Visible", "Perceptible", "Heavy Weight",
9876 "Backup", "A Services", "Home", "Previous",
9877 "B Services", "Background"
9878 };
9879
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009880 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009881 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009882 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009883 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009884 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009885
9886 int opti = 0;
9887 while (opti < args.length) {
9888 String opt = args[opti];
9889 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9890 break;
9891 }
9892 opti++;
9893 if ("-a".equals(opt)) {
9894 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009895 } else if ("--oom".equals(opt)) {
9896 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009897 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009898 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009899 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009900 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009901 pw.println("If [process] is specified it can be the name or ");
9902 pw.println("pid of a specific process to dump.");
9903 return;
9904 } else {
9905 pw.println("Unknown argument: " + opt + "; use -h for help");
9906 }
9907 }
9908
9909 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009910 if (procs == null) {
9911 return;
9912 }
9913
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009914 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 long uptime = SystemClock.uptimeMillis();
9916 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009917
9918 if (procs.size() == 1 || isCheckinRequest) {
9919 dumpAll = true;
9920 }
9921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 if (isCheckinRequest) {
9923 // short checkin version
9924 pw.println(uptime + "," + realtime);
9925 pw.flush();
9926 } else {
9927 pw.println("Applications Memory Usage (kB):");
9928 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9929 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009930
Dianne Hackbornb437e092011-08-05 17:50:29 -07009931 String[] innerArgs = new String[args.length-opti];
9932 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9933
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009934 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9935 long nativePss=0, dalvikPss=0, otherPss=0;
9936 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9937
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009938 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9939 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9940 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009941
9942 long totalPss = 0;
9943
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009944 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9945 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009946 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009947 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009948 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9949 pw.flush();
9950 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009951 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009952 if (dumpAll) {
9953 try {
9954 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9955 } catch (RemoteException e) {
9956 if (!isCheckinRequest) {
9957 pw.println("Got RemoteException!");
9958 pw.flush();
9959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009960 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009961 } else {
9962 mi = new Debug.MemoryInfo();
9963 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009964 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009965
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009966 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009967 long myTotalPss = mi.getTotalPss();
9968 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009969 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009970 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009971 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009972
9973 nativePss += mi.nativePss;
9974 dalvikPss += mi.dalvikPss;
9975 otherPss += mi.otherPss;
9976 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9977 long mem = mi.getOtherPss(j);
9978 miscPss[j] += mem;
9979 otherPss -= mem;
9980 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009981
9982 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009983 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9984 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009985 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009986 if (oomProcs[oomIndex] == null) {
9987 oomProcs[oomIndex] = new ArrayList<MemItem>();
9988 }
9989 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009990 break;
9991 }
9992 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009994 }
9995 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009996
9997 if (!isCheckinRequest && procs.size() > 1) {
9998 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9999
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010000 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10001 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10002 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010003 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010004 String label = Debug.MemoryInfo.getOtherLabel(j);
10005 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010006 }
10007
Dianne Hackbornb437e092011-08-05 17:50:29 -070010008 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10009 for (int j=0; j<oomPss.length; j++) {
10010 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010011 String label = DUMP_MEM_OOM_LABEL[j];
10012 MemItem item = new MemItem(label, label, oomPss[j],
10013 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010014 item.subitems = oomProcs[j];
10015 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010016 }
10017 }
10018
Dianne Hackborn672342c2011-11-29 11:29:02 -080010019 if (outTag != null || outStack != null) {
10020 if (outTag != null) {
10021 appendMemBucket(outTag, totalPss, "total", false);
10022 }
10023 if (outStack != null) {
10024 appendMemBucket(outStack, totalPss, "total", true);
10025 }
10026 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010027 for (int i=0; i<oomMems.size(); i++) {
10028 MemItem miCat = oomMems.get(i);
10029 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10030 continue;
10031 }
10032 if (miCat.id < ProcessList.SERVICE_ADJ
10033 || miCat.id == ProcessList.HOME_APP_ADJ
10034 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010035 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10036 outTag.append(" / ");
10037 }
10038 if (outStack != null) {
10039 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10040 if (firstLine) {
10041 outStack.append(":");
10042 firstLine = false;
10043 }
10044 outStack.append("\n\t at ");
10045 } else {
10046 outStack.append("$");
10047 }
10048 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010049 for (int j=0; j<miCat.subitems.size(); j++) {
10050 MemItem mi = miCat.subitems.get(j);
10051 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010052 if (outTag != null) {
10053 outTag.append(" ");
10054 }
10055 if (outStack != null) {
10056 outStack.append("$");
10057 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010058 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010059 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10060 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10061 }
10062 if (outStack != null) {
10063 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10064 }
10065 }
10066 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10067 outStack.append("(");
10068 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10069 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10070 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10071 outStack.append(":");
10072 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10073 }
10074 }
10075 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010076 }
10077 }
10078 }
10079 }
10080
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010081 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010082 pw.println();
10083 pw.println("Total PSS by process:");
10084 dumpMemItems(pw, " ", procMems, true);
10085 pw.println();
10086 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010087 pw.println("Total PSS by OOM adjustment:");
10088 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010089 if (!oomOnly) {
10090 PrintWriter out = categoryPw != null ? categoryPw : pw;
10091 out.println();
10092 out.println("Total PSS by category:");
10093 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010094 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010095 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010096 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010098 }
10099
10100 /**
10101 * Searches array of arguments for the specified string
10102 * @param args array of argument strings
10103 * @param value value to search for
10104 * @return true if the value is contained in the array
10105 */
10106 private static boolean scanArgs(String[] args, String value) {
10107 if (args != null) {
10108 for (String arg : args) {
10109 if (value.equals(arg)) {
10110 return true;
10111 }
10112 }
10113 }
10114 return false;
10115 }
10116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010117 private final void killServicesLocked(ProcessRecord app,
10118 boolean allowRestart) {
10119 // Report disconnected services.
10120 if (false) {
10121 // XXX we are letting the client link to the service for
10122 // death notifications.
10123 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010124 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010125 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010126 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010127 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010128 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010129 = r.connections.values().iterator();
10130 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010131 ArrayList<ConnectionRecord> cl = jt.next();
10132 for (int i=0; i<cl.size(); i++) {
10133 ConnectionRecord c = cl.get(i);
10134 if (c.binding.client != app) {
10135 try {
10136 //c.conn.connected(r.className, null);
10137 } catch (Exception e) {
10138 // todo: this should be asynchronous!
10139 Slog.w(TAG, "Exception thrown disconnected servce "
10140 + r.shortName
10141 + " from app " + app.processName, e);
10142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 }
10144 }
10145 }
10146 }
10147 }
10148 }
10149 }
10150
10151 // Clean up any connections this application has to other services.
10152 if (app.connections.size() > 0) {
10153 Iterator<ConnectionRecord> it = app.connections.iterator();
10154 while (it.hasNext()) {
10155 ConnectionRecord r = it.next();
10156 removeConnectionLocked(r, app, null);
10157 }
10158 }
10159 app.connections.clear();
10160
10161 if (app.services.size() != 0) {
10162 // Any services running in the application need to be placed
10163 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010164 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010165 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010166 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010167 synchronized (sr.stats.getBatteryStats()) {
10168 sr.stats.stopLaunchedLocked();
10169 }
10170 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010171 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010172 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010173 if (mStoppingServices.remove(sr)) {
10174 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10175 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010176
10177 boolean hasClients = sr.bindings.size() > 0;
10178 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010179 Iterator<IntentBindRecord> bindings
10180 = sr.bindings.values().iterator();
10181 while (bindings.hasNext()) {
10182 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010183 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010184 + ": shouldUnbind=" + b.hasBound);
10185 b.binder = null;
10186 b.requested = b.received = b.hasBound = false;
10187 }
10188 }
10189
Dianne Hackborn070783f2010-12-29 16:46:28 -080010190 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10191 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010192 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010194 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010195 sr.crashCount, sr.shortName, app.pid);
10196 bringDownServiceLocked(sr, true);
10197 } else if (!allowRestart) {
10198 bringDownServiceLocked(sr, true);
10199 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010200 boolean canceled = scheduleServiceRestartLocked(sr, true);
10201
10202 // Should the service remain running? Note that in the
10203 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010204 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010205 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10206 if (sr.pendingStarts.size() == 0) {
10207 sr.startRequested = false;
10208 if (!hasClients) {
10209 // Whoops, no reason to restart!
10210 bringDownServiceLocked(sr, true);
10211 }
10212 }
10213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010214 }
10215 }
10216
10217 if (!allowRestart) {
10218 app.services.clear();
10219 }
10220 }
10221
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010222 // Make sure we have no more records on the stopping list.
10223 int i = mStoppingServices.size();
10224 while (i > 0) {
10225 i--;
10226 ServiceRecord sr = mStoppingServices.get(i);
10227 if (sr.app == app) {
10228 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010229 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010230 }
10231 }
10232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010233 app.executingServices.clear();
10234 }
10235
10236 private final void removeDyingProviderLocked(ProcessRecord proc,
10237 ContentProviderRecord cpr) {
10238 synchronized (cpr) {
10239 cpr.launchingApp = null;
10240 cpr.notifyAll();
10241 }
10242
Amith Yamasani742a6712011-05-04 14:49:28 -070010243 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010244 String names[] = cpr.info.authority.split(";");
10245 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010246 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010247 }
10248
10249 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10250 while (cit.hasNext()) {
10251 ProcessRecord capp = cit.next();
10252 if (!capp.persistent && capp.thread != null
10253 && capp.pid != 0
10254 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010255 Slog.i(TAG, "Kill " + capp.processName
10256 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010257 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010258 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010259 capp.processName, capp.setAdj, "dying provider "
10260 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010261 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010262 }
10263 }
10264
10265 mLaunchingProviders.remove(cpr);
10266 }
10267
10268 /**
10269 * Main code for cleaning up a process when it has gone away. This is
10270 * called both as a result of the process dying, or directly when stopping
10271 * a process when running in single process mode.
10272 */
10273 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010274 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010275 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010276 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010277 }
10278
Dianne Hackborn36124872009-10-08 16:22:03 -070010279 mProcessesToGc.remove(app);
10280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010281 // Dismiss any open dialogs.
10282 if (app.crashDialog != null) {
10283 app.crashDialog.dismiss();
10284 app.crashDialog = null;
10285 }
10286 if (app.anrDialog != null) {
10287 app.anrDialog.dismiss();
10288 app.anrDialog = null;
10289 }
10290 if (app.waitDialog != null) {
10291 app.waitDialog.dismiss();
10292 app.waitDialog = null;
10293 }
10294
10295 app.crashing = false;
10296 app.notResponding = false;
10297
10298 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010299 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010300 app.thread = null;
10301 app.forcingToForeground = null;
10302 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010303 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010304 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010305 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010306
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010307 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308
10309 boolean restart = false;
10310
10311 int NL = mLaunchingProviders.size();
10312
10313 // Remove published content providers.
10314 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010315 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010316 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010317 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010318 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010319 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010320
10321 // See if someone is waiting for this provider... in which
10322 // case we don't remove it, but just let it restart.
10323 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010324 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010325 for (; i<NL; i++) {
10326 if (mLaunchingProviders.get(i) == cpr) {
10327 restart = true;
10328 break;
10329 }
10330 }
10331 } else {
10332 i = NL;
10333 }
10334
10335 if (i >= NL) {
10336 removeDyingProviderLocked(app, cpr);
10337 NL = mLaunchingProviders.size();
10338 }
10339 }
10340 app.pubProviders.clear();
10341 }
10342
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010343 // Take care of any launching providers waiting for this process.
10344 if (checkAppInLaunchingProvidersLocked(app, false)) {
10345 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010346 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010348 // Unregister from connected content providers.
10349 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010350 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010351 while (it.hasNext()) {
10352 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10353 cpr.clients.remove(app);
10354 }
10355 app.conProviders.clear();
10356 }
10357
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010358 // At this point there may be remaining entries in mLaunchingProviders
10359 // where we were the only one waiting, so they are no longer of use.
10360 // Look for these and clean up if found.
10361 // XXX Commented out for now. Trying to figure out a way to reproduce
10362 // the actual situation to identify what is actually going on.
10363 if (false) {
10364 for (int i=0; i<NL; i++) {
10365 ContentProviderRecord cpr = (ContentProviderRecord)
10366 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010367 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010368 synchronized (cpr) {
10369 cpr.launchingApp = null;
10370 cpr.notifyAll();
10371 }
10372 }
10373 }
10374 }
10375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010376 skipCurrentReceiverLocked(app);
10377
10378 // Unregister any receivers.
10379 if (app.receivers.size() > 0) {
10380 Iterator<ReceiverList> it = app.receivers.iterator();
10381 while (it.hasNext()) {
10382 removeReceiverLocked(it.next());
10383 }
10384 app.receivers.clear();
10385 }
10386
Christopher Tate181fafa2009-05-14 11:12:14 -070010387 // If the app is undergoing backup, tell the backup manager about it
10388 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010389 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010390 try {
10391 IBackupManager bm = IBackupManager.Stub.asInterface(
10392 ServiceManager.getService(Context.BACKUP_SERVICE));
10393 bm.agentDisconnected(app.info.packageName);
10394 } catch (RemoteException e) {
10395 // can't happen; backup manager is local
10396 }
10397 }
10398
Jeff Sharkey287bd832011-05-28 19:36:26 -070010399 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010401 // If the caller is restarting this app, then leave it in its
10402 // current lists and let the caller take care of it.
10403 if (restarting) {
10404 return;
10405 }
10406
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010407 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010408 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010409 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010410 mProcessNames.remove(app.processName, app.uid);
10411 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010412 if (mHeavyWeightProcess == app) {
10413 mHeavyWeightProcess = null;
10414 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010416 } else if (!app.removed) {
10417 // This app is persistent, so we need to keep its record around.
10418 // If it is not already on the pending app list, add it there
10419 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010420 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10421 mPersistentStartingProcesses.add(app);
10422 restart = true;
10423 }
10424 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010425 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10426 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010427 mProcessesOnHold.remove(app);
10428
The Android Open Source Project4df24232009-03-05 14:34:35 -080010429 if (app == mHomeProcess) {
10430 mHomeProcess = null;
10431 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010432 if (app == mPreviousProcess) {
10433 mPreviousProcess = null;
10434 }
10435
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010436 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010437 // We have components that still need to be running in the
10438 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010439 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010440 startProcessLocked(app, "restart", app.processName);
10441 } else if (app.pid > 0 && app.pid != MY_PID) {
10442 // Goodbye!
10443 synchronized (mPidsSelfLocked) {
10444 mPidsSelfLocked.remove(app.pid);
10445 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10446 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010447 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010448 }
10449 }
10450
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010451 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10452 // Look through the content providers we are waiting to have launched,
10453 // and if any run in this process then either schedule a restart of
10454 // the process or kill the client waiting for it if this process has
10455 // gone bad.
10456 int NL = mLaunchingProviders.size();
10457 boolean restart = false;
10458 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010459 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010460 if (cpr.launchingApp == app) {
10461 if (!alwaysBad && !app.bad) {
10462 restart = true;
10463 } else {
10464 removeDyingProviderLocked(app, cpr);
10465 NL = mLaunchingProviders.size();
10466 }
10467 }
10468 }
10469 return restart;
10470 }
10471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472 // =========================================================
10473 // SERVICES
10474 // =========================================================
10475
10476 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10477 ActivityManager.RunningServiceInfo info =
10478 new ActivityManager.RunningServiceInfo();
10479 info.service = r.name;
10480 if (r.app != null) {
10481 info.pid = r.app.pid;
10482 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010483 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 info.process = r.processName;
10485 info.foreground = r.isForeground;
10486 info.activeSince = r.createTime;
10487 info.started = r.startRequested;
10488 info.clientCount = r.connections.size();
10489 info.crashCount = r.crashCount;
10490 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010491 if (r.isForeground) {
10492 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10493 }
10494 if (r.startRequested) {
10495 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10496 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010497 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010498 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10499 }
10500 if (r.app != null && r.app.persistent) {
10501 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10502 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010503
10504 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10505 for (int i=0; i<connl.size(); i++) {
10506 ConnectionRecord conn = connl.get(i);
10507 if (conn.clientLabel != 0) {
10508 info.clientPackage = conn.binding.client.info.packageName;
10509 info.clientLabel = conn.clientLabel;
10510 return info;
10511 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010512 }
10513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 return info;
10515 }
10516
10517 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10518 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010519 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010520 synchronized (this) {
10521 ArrayList<ActivityManager.RunningServiceInfo> res
10522 = new ArrayList<ActivityManager.RunningServiceInfo>();
10523
Amith Yamasani742a6712011-05-04 14:49:28 -070010524 int userId = UserId.getUserId(Binder.getCallingUid());
10525 if (mServiceMap.getAllServices(userId).size() > 0) {
10526 Iterator<ServiceRecord> it
10527 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010528 while (it.hasNext() && res.size() < maxNum) {
10529 res.add(makeRunningServiceInfoLocked(it.next()));
10530 }
10531 }
10532
10533 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10534 ServiceRecord r = mRestartingServices.get(i);
10535 ActivityManager.RunningServiceInfo info =
10536 makeRunningServiceInfoLocked(r);
10537 info.restarting = r.nextRestartTime;
10538 res.add(info);
10539 }
10540
10541 return res;
10542 }
10543 }
10544
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010545 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010546 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010547 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010548 int userId = UserId.getUserId(Binder.getCallingUid());
10549 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010550 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010551 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10552 for (int i=0; i<conn.size(); i++) {
10553 if (conn.get(i).clientIntent != null) {
10554 return conn.get(i).clientIntent;
10555 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010556 }
10557 }
10558 }
10559 }
10560 return null;
10561 }
10562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 private final ServiceRecord findServiceLocked(ComponentName name,
10564 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010565 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 return r == token ? r : null;
10567 }
10568
10569 private final class ServiceLookupResult {
10570 final ServiceRecord record;
10571 final String permission;
10572
10573 ServiceLookupResult(ServiceRecord _record, String _permission) {
10574 record = _record;
10575 permission = _permission;
10576 }
10577 };
10578
10579 private ServiceLookupResult findServiceLocked(Intent service,
10580 String resolvedType) {
10581 ServiceRecord r = null;
10582 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010583 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010584 }
10585 if (r == null) {
10586 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010587 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 }
10589
10590 if (r == null) {
10591 try {
10592 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010593 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010594 service, resolvedType, 0);
10595 ServiceInfo sInfo =
10596 rInfo != null ? rInfo.serviceInfo : null;
10597 if (sInfo == null) {
10598 return null;
10599 }
10600
10601 ComponentName name = new ComponentName(
10602 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010603 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604 } catch (RemoteException ex) {
10605 // pm is in same process, this will never happen.
10606 }
10607 }
10608 if (r != null) {
10609 int callingPid = Binder.getCallingPid();
10610 int callingUid = Binder.getCallingUid();
10611 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010612 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010614 if (!r.exported) {
10615 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10616 + " from pid=" + callingPid
10617 + ", uid=" + callingUid
10618 + " that is not exported from uid " + r.appInfo.uid);
10619 return new ServiceLookupResult(null, "not exported from uid "
10620 + r.appInfo.uid);
10621 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010622 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010623 + " from pid=" + callingPid
10624 + ", uid=" + callingUid
10625 + " requires " + r.permission);
10626 return new ServiceLookupResult(null, r.permission);
10627 }
10628 return new ServiceLookupResult(r, null);
10629 }
10630 return null;
10631 }
10632
10633 private class ServiceRestarter implements Runnable {
10634 private ServiceRecord mService;
10635
10636 void setService(ServiceRecord service) {
10637 mService = service;
10638 }
10639
10640 public void run() {
10641 synchronized(ActivityManagerService.this) {
10642 performServiceRestartLocked(mService);
10643 }
10644 }
10645 }
10646
10647 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010648 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010649 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010650 if (DEBUG_SERVICE)
10651 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010652 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010654 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010655 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010656 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010657 if (r == null) {
10658 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010659 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010661 if (r == null) {
10662 try {
10663 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010664 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010665 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 ServiceInfo sInfo =
10667 rInfo != null ? rInfo.serviceInfo : null;
10668 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010669 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010670 ": not found");
10671 return null;
10672 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010673 if (userId > 0) {
10674 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 ComponentName name = new ComponentName(
10677 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010678 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010679 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010680 Intent.FilterComparison filter = new Intent.FilterComparison(
10681 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010682 ServiceRestarter res = new ServiceRestarter();
10683 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10684 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10685 synchronized (stats) {
10686 ss = stats.getServiceStatsLocked(
10687 sInfo.applicationInfo.uid, sInfo.packageName,
10688 sInfo.name);
10689 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010690 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010692 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10693 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010694
10695 // Make sure this component isn't in the pending list.
10696 int N = mPendingServices.size();
10697 for (int i=0; i<N; i++) {
10698 ServiceRecord pr = mPendingServices.get(i);
10699 if (pr.name.equals(name)) {
10700 mPendingServices.remove(i);
10701 i--;
10702 N--;
10703 }
10704 }
10705 }
10706 } catch (RemoteException ex) {
10707 // pm is in same process, this will never happen.
10708 }
10709 }
10710 if (r != null) {
10711 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010712 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010713 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010714 if (!r.exported) {
10715 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10716 + " from pid=" + callingPid
10717 + ", uid=" + callingUid
10718 + " that is not exported from uid " + r.appInfo.uid);
10719 return new ServiceLookupResult(null, "not exported from uid "
10720 + r.appInfo.uid);
10721 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010722 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010723 + " from pid=" + callingPid
10724 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010725 + " requires " + r.permission);
10726 return new ServiceLookupResult(null, r.permission);
10727 }
10728 return new ServiceLookupResult(r, null);
10729 }
10730 return null;
10731 }
10732
Dianne Hackborn287952c2010-09-22 22:34:31 -070010733 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10734 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10735 + why + " of " + r + " in app " + r.app);
10736 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10737 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 long now = SystemClock.uptimeMillis();
10739 if (r.executeNesting == 0 && r.app != null) {
10740 if (r.app.executingServices.size() == 0) {
10741 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10742 msg.obj = r.app;
10743 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10744 }
10745 r.app.executingServices.add(r);
10746 }
10747 r.executeNesting++;
10748 r.executingStart = now;
10749 }
10750
10751 private final void sendServiceArgsLocked(ServiceRecord r,
10752 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010753 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010754 if (N == 0) {
10755 return;
10756 }
10757
Dianne Hackborn39792d22010-08-19 18:01:52 -070010758 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010760 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010761 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10762 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010763 if (si.intent == null && N > 1) {
10764 // If somehow we got a dummy null intent in the middle,
10765 // then skip it. DO NOT skip a null intent when it is
10766 // the only one in the list -- this is to support the
10767 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010768 continue;
10769 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010770 si.deliveredTime = SystemClock.uptimeMillis();
10771 r.deliveredStarts.add(si);
10772 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010773 if (si.neededGrants != null) {
10774 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10775 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010776 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010777 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010778 if (!oomAdjusted) {
10779 oomAdjusted = true;
10780 updateOomAdjLocked(r.app);
10781 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010782 int flags = 0;
10783 if (si.deliveryCount > 0) {
10784 flags |= Service.START_FLAG_RETRY;
10785 }
10786 if (si.doneExecutingCount > 0) {
10787 flags |= Service.START_FLAG_REDELIVERY;
10788 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010789 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010790 } catch (RemoteException e) {
10791 // Remote process gone... we'll let the normal cleanup take
10792 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010793 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010794 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010796 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010797 break;
10798 }
10799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010800 }
10801
10802 private final boolean requestServiceBindingLocked(ServiceRecord r,
10803 IntentBindRecord i, boolean rebind) {
10804 if (r.app == null || r.app.thread == null) {
10805 // If service is not currently running, can't yet bind.
10806 return false;
10807 }
10808 if ((!i.requested || rebind) && i.apps.size() > 0) {
10809 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010810 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010811 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10812 if (!rebind) {
10813 i.requested = true;
10814 }
10815 i.hasBound = true;
10816 i.doRebind = false;
10817 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010818 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 return false;
10820 }
10821 }
10822 return true;
10823 }
10824
10825 private final void requestServiceBindingsLocked(ServiceRecord r) {
10826 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10827 while (bindings.hasNext()) {
10828 IntentBindRecord i = bindings.next();
10829 if (!requestServiceBindingLocked(r, i, false)) {
10830 break;
10831 }
10832 }
10833 }
10834
10835 private final void realStartServiceLocked(ServiceRecord r,
10836 ProcessRecord app) throws RemoteException {
10837 if (app.thread == null) {
10838 throw new RemoteException();
10839 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010840 if (DEBUG_MU)
10841 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010842 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010843 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010844 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845
10846 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010847 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010848 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010849
10850 boolean created = false;
10851 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010852 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010853 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010854 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010856 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 synchronized (r.stats.getBatteryStats()) {
10858 r.stats.startLaunchedLocked();
10859 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010860 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010861 app.thread.scheduleCreateService(r, r.serviceInfo,
10862 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010863 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010864 created = true;
10865 } finally {
10866 if (!created) {
10867 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010868 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 }
10870 }
10871
10872 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010873
10874 // If the service is in the started state, and there are no
10875 // pending arguments, then fake up one so its onStartCommand() will
10876 // be called.
10877 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010878 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010879 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010880 }
10881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 sendServiceArgsLocked(r, true);
10883 }
10884
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010885 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10886 boolean allowCancel) {
10887 boolean canceled = false;
10888
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010889 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010890 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010891 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010892
Dianne Hackborn070783f2010-12-29 16:46:28 -080010893 if ((r.serviceInfo.applicationInfo.flags
10894 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10895 minDuration /= 4;
10896 }
10897
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010898 // Any delivered but not yet finished starts should be put back
10899 // on the pending list.
10900 final int N = r.deliveredStarts.size();
10901 if (N > 0) {
10902 for (int i=N-1; i>=0; i--) {
10903 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010904 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010905 if (si.intent == null) {
10906 // We'll generate this again if needed.
10907 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10908 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10909 r.pendingStarts.add(0, si);
10910 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10911 dur *= 2;
10912 if (minDuration < dur) minDuration = dur;
10913 if (resetTime < dur) resetTime = dur;
10914 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010915 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010916 + r.name);
10917 canceled = true;
10918 }
10919 }
10920 r.deliveredStarts.clear();
10921 }
10922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 r.totalRestartCount++;
10924 if (r.restartDelay == 0) {
10925 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010926 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 } else {
10928 // If it has been a "reasonably long time" since the service
10929 // was started, then reset our restart duration back to
10930 // the beginning, so we don't infinitely increase the duration
10931 // on a service that just occasionally gets killed (which is
10932 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010933 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010935 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010936 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010937 if ((r.serviceInfo.applicationInfo.flags
10938 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10939 // Services in peristent processes will restart much more
10940 // quickly, since they are pretty important. (Think SystemUI).
10941 r.restartDelay += minDuration/2;
10942 } else {
10943 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10944 if (r.restartDelay < minDuration) {
10945 r.restartDelay = minDuration;
10946 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 }
10949 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010950
10951 r.nextRestartTime = now + r.restartDelay;
10952
10953 // Make sure that we don't end up restarting a bunch of services
10954 // all at the same time.
10955 boolean repeat;
10956 do {
10957 repeat = false;
10958 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10959 ServiceRecord r2 = mRestartingServices.get(i);
10960 if (r2 != r && r.nextRestartTime
10961 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10962 && r.nextRestartTime
10963 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10964 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10965 r.restartDelay = r.nextRestartTime - now;
10966 repeat = true;
10967 break;
10968 }
10969 }
10970 } while (repeat);
10971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010972 if (!mRestartingServices.contains(r)) {
10973 mRestartingServices.add(r);
10974 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010975
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010976 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010978 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010979 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010981 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010983 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 r.shortName, r.restartDelay);
10985
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010986 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 }
10988
10989 final void performServiceRestartLocked(ServiceRecord r) {
10990 if (!mRestartingServices.contains(r)) {
10991 return;
10992 }
10993 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10994 }
10995
10996 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10997 if (r.restartDelay == 0) {
10998 return false;
10999 }
11000 r.resetRestartCounter();
11001 mRestartingServices.remove(r);
11002 mHandler.removeCallbacks(r.restarter);
11003 return true;
11004 }
11005
11006 private final boolean bringUpServiceLocked(ServiceRecord r,
11007 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011008 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 //r.dump(" ");
11010
Dianne Hackborn36124872009-10-08 16:22:03 -070011011 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 sendServiceArgsLocked(r, false);
11013 return true;
11014 }
11015
11016 if (!whileRestarting && r.restartDelay > 0) {
11017 // If waiting for a restart, then do nothing.
11018 return true;
11019 }
11020
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011021 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011023 // We are now bringing the service up, so no longer in the
11024 // restarting state.
11025 mRestartingServices.remove(r);
11026
Dianne Hackborne7f97212011-02-24 14:40:20 -080011027 // Service is now being launched, its package can't be stopped.
11028 try {
11029 AppGlobals.getPackageManager().setPackageStoppedState(
11030 r.packageName, false);
11031 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011032 } catch (IllegalArgumentException e) {
11033 Slog.w(TAG, "Failed trying to unstop package "
11034 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011035 }
11036
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011037 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011038 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011039 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011041 if (!isolated) {
11042 app = getProcessRecordLocked(appName, r.appInfo.uid);
11043 if (DEBUG_MU)
11044 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11045 if (app != null && app.thread != null) {
11046 try {
11047 app.addPackage(r.appInfo.packageName);
11048 realStartServiceLocked(r, app);
11049 return true;
11050 } catch (RemoteException e) {
11051 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11052 }
11053
11054 // If a dead object exception was thrown -- fall through to
11055 // restart the application.
11056 }
11057 } else {
11058 // If this service runs in an isolated process, then each time
11059 // we call startProcessLocked() we will get a new isolated
11060 // process, starting another process if we are currently waiting
11061 // for a previous process to come up. To deal with this, we store
11062 // in the service any current isolated process it is running in or
11063 // waiting to have come up.
11064 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011065 }
11066
Dianne Hackborn36124872009-10-08 16:22:03 -070011067 // Not running -- get it started, and enqueue this service record
11068 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011069 if (app == null) {
11070 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11071 "service", r.name, false, isolated)) == null) {
11072 Slog.w(TAG, "Unable to launch app "
11073 + r.appInfo.packageName + "/"
11074 + r.appInfo.uid + " for service "
11075 + r.intent.getIntent() + ": process is bad");
11076 bringDownServiceLocked(r, true);
11077 return false;
11078 }
11079 if (isolated) {
11080 r.isolatedProc = app;
11081 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011082 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011085 mPendingServices.add(r);
11086 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011088 return true;
11089 }
11090
11091 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011092 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011093 //r.dump(" ");
11094
11095 // Does it still need to run?
11096 if (!force && r.startRequested) {
11097 return;
11098 }
11099 if (r.connections.size() > 0) {
11100 if (!force) {
11101 // XXX should probably keep a count of the number of auto-create
11102 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011103 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011105 ArrayList<ConnectionRecord> cr = it.next();
11106 for (int i=0; i<cr.size(); i++) {
11107 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11108 return;
11109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 }
11111 }
11112 }
11113
11114 // Report to all of the connections that the service is no longer
11115 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011116 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011118 ArrayList<ConnectionRecord> c = it.next();
11119 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011120 ConnectionRecord cr = c.get(i);
11121 // There is still a connection to the service that is
11122 // being brought down. Mark it as dead.
11123 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011124 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011125 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011126 } catch (Exception e) {
11127 Slog.w(TAG, "Failure disconnecting service " + r.name +
11128 " to connection " + c.get(i).conn.asBinder() +
11129 " (in " + c.get(i).binding.client.processName + ")", e);
11130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131 }
11132 }
11133 }
11134
11135 // Tell the service that it has been unbound.
11136 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11137 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11138 while (it.hasNext()) {
11139 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011140 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 + ": hasBound=" + ibr.hasBound);
11142 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11143 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011144 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145 updateOomAdjLocked(r.app);
11146 ibr.hasBound = false;
11147 r.app.thread.scheduleUnbindService(r,
11148 ibr.intent.getIntent());
11149 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011150 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011151 + r.shortName, e);
11152 serviceDoneExecutingLocked(r, true);
11153 }
11154 }
11155 }
11156 }
11157
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011158 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011159 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011160 System.identityHashCode(r), r.shortName,
11161 (r.app != null) ? r.app.pid : -1);
11162
Amith Yamasani742a6712011-05-04 14:49:28 -070011163 mServiceMap.removeServiceByName(r.name, r.userId);
11164 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 r.totalRestartCount = 0;
11166 unscheduleServiceRestartLocked(r);
11167
11168 // Also make sure it is not on the pending list.
11169 int N = mPendingServices.size();
11170 for (int i=0; i<N; i++) {
11171 if (mPendingServices.get(i) == r) {
11172 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011173 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 i--;
11175 N--;
11176 }
11177 }
11178
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011179 r.cancelNotification();
11180 r.isForeground = false;
11181 r.foregroundId = 0;
11182 r.foregroundNoti = null;
11183
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011184 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011185 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011186 r.pendingStarts.clear();
11187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 if (r.app != null) {
11189 synchronized (r.stats.getBatteryStats()) {
11190 r.stats.stopLaunchedLocked();
11191 }
11192 r.app.services.remove(r);
11193 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011194 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011195 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196 mStoppingServices.add(r);
11197 updateOomAdjLocked(r.app);
11198 r.app.thread.scheduleStopService(r);
11199 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011200 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 + r.shortName, e);
11202 serviceDoneExecutingLocked(r, true);
11203 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011204 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011206 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011207 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208 }
11209 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011210 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011211 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011212 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011213
11214 if (r.bindings.size() > 0) {
11215 r.bindings.clear();
11216 }
11217
11218 if (r.restarter instanceof ServiceRestarter) {
11219 ((ServiceRestarter)r.restarter).setService(null);
11220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221 }
11222
11223 ComponentName startServiceLocked(IApplicationThread caller,
11224 Intent service, String resolvedType,
11225 int callingPid, int callingUid) {
11226 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011227 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011228 + " type=" + resolvedType + " args=" + service.getExtras());
11229
11230 if (caller != null) {
11231 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11232 if (callerApp == null) {
11233 throw new SecurityException(
11234 "Unable to find app for caller " + caller
11235 + " (pid=" + Binder.getCallingPid()
11236 + ") when starting service " + service);
11237 }
11238 }
11239
11240 ServiceLookupResult res =
11241 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011242 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 if (res == null) {
11244 return null;
11245 }
11246 if (res.record == null) {
11247 return new ComponentName("!", res.permission != null
11248 ? res.permission : "private to package");
11249 }
11250 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011251 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11252 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011253 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011254 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011255 }
11256 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011257 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011258 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011259 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 r.lastActivity = SystemClock.uptimeMillis();
11261 synchronized (r.stats.getBatteryStats()) {
11262 r.stats.startRunningLocked();
11263 }
11264 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11265 return new ComponentName("!", "Service process is bad");
11266 }
11267 return r.name;
11268 }
11269 }
11270
11271 public ComponentName startService(IApplicationThread caller, Intent service,
11272 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011273 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 // Refuse possible leaked file descriptors
11275 if (service != null && service.hasFileDescriptors() == true) {
11276 throw new IllegalArgumentException("File descriptors passed in Intent");
11277 }
11278
Amith Yamasani742a6712011-05-04 14:49:28 -070011279 if (DEBUG_SERVICE)
11280 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011281 synchronized(this) {
11282 final int callingPid = Binder.getCallingPid();
11283 final int callingUid = Binder.getCallingUid();
11284 final long origId = Binder.clearCallingIdentity();
11285 ComponentName res = startServiceLocked(caller, service,
11286 resolvedType, callingPid, callingUid);
11287 Binder.restoreCallingIdentity(origId);
11288 return res;
11289 }
11290 }
11291
11292 ComponentName startServiceInPackage(int uid,
11293 Intent service, String resolvedType) {
11294 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011295 if (DEBUG_SERVICE)
11296 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 final long origId = Binder.clearCallingIdentity();
11298 ComponentName res = startServiceLocked(null, service,
11299 resolvedType, -1, uid);
11300 Binder.restoreCallingIdentity(origId);
11301 return res;
11302 }
11303 }
11304
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011305 private void stopServiceLocked(ServiceRecord service) {
11306 synchronized (service.stats.getBatteryStats()) {
11307 service.stats.stopRunningLocked();
11308 }
11309 service.startRequested = false;
11310 service.callStart = false;
11311 bringDownServiceLocked(service, false);
11312 }
11313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 public int stopService(IApplicationThread caller, Intent service,
11315 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011316 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 // Refuse possible leaked file descriptors
11318 if (service != null && service.hasFileDescriptors() == true) {
11319 throw new IllegalArgumentException("File descriptors passed in Intent");
11320 }
11321
11322 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011323 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324 + " type=" + resolvedType);
11325
11326 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11327 if (caller != null && callerApp == null) {
11328 throw new SecurityException(
11329 "Unable to find app for caller " + caller
11330 + " (pid=" + Binder.getCallingPid()
11331 + ") when stopping service " + service);
11332 }
11333
11334 // If this service is active, make sure it is stopped.
11335 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11336 if (r != null) {
11337 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011338 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011339 try {
11340 stopServiceLocked(r.record);
11341 } finally {
11342 Binder.restoreCallingIdentity(origId);
11343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 return 1;
11345 }
11346 return -1;
11347 }
11348 }
11349
11350 return 0;
11351 }
11352
11353 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011354 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355 // Refuse possible leaked file descriptors
11356 if (service != null && service.hasFileDescriptors() == true) {
11357 throw new IllegalArgumentException("File descriptors passed in Intent");
11358 }
11359
11360 IBinder ret = null;
11361
11362 synchronized(this) {
11363 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11364
11365 if (r != null) {
11366 // r.record is null if findServiceLocked() failed the caller permission check
11367 if (r.record == null) {
11368 throw new SecurityException(
11369 "Permission Denial: Accessing service " + r.record.name
11370 + " from pid=" + Binder.getCallingPid()
11371 + ", uid=" + Binder.getCallingUid()
11372 + " requires " + r.permission);
11373 }
11374 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11375 if (ib != null) {
11376 ret = ib.binder;
11377 }
11378 }
11379 }
11380
11381 return ret;
11382 }
11383
11384 public boolean stopServiceToken(ComponentName className, IBinder token,
11385 int startId) {
11386 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011387 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 + " " + token + " startId=" + startId);
11389 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011390 if (r != null) {
11391 if (startId >= 0) {
11392 // Asked to only stop if done with all work. Note that
11393 // to avoid leaks, we will take this as dropping all
11394 // start items up to and including this one.
11395 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11396 if (si != null) {
11397 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011398 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11399 cur.removeUriPermissionsLocked();
11400 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011401 break;
11402 }
11403 }
11404 }
11405
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011406 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011407 return false;
11408 }
11409
11410 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011411 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011412 + " is last, but have " + r.deliveredStarts.size()
11413 + " remaining args");
11414 }
11415 }
11416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011417 synchronized (r.stats.getBatteryStats()) {
11418 r.stats.stopRunningLocked();
11419 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011420 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011421 }
11422 final long origId = Binder.clearCallingIdentity();
11423 bringDownServiceLocked(r, false);
11424 Binder.restoreCallingIdentity(origId);
11425 return true;
11426 }
11427 }
11428 return false;
11429 }
11430
11431 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011432 int id, Notification notification, boolean removeNotification) {
11433 final long origId = Binder.clearCallingIdentity();
11434 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011435 synchronized(this) {
11436 ServiceRecord r = findServiceLocked(className, token);
11437 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011438 if (id != 0) {
11439 if (notification == null) {
11440 throw new IllegalArgumentException("null notification");
11441 }
11442 if (r.foregroundId != id) {
11443 r.cancelNotification();
11444 r.foregroundId = id;
11445 }
11446 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11447 r.foregroundNoti = notification;
11448 r.isForeground = true;
11449 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011450 if (r.app != null) {
11451 updateServiceForegroundLocked(r.app, true);
11452 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011453 } else {
11454 if (r.isForeground) {
11455 r.isForeground = false;
11456 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011457 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011458 updateServiceForegroundLocked(r.app, true);
11459 }
11460 }
11461 if (removeNotification) {
11462 r.cancelNotification();
11463 r.foregroundId = 0;
11464 r.foregroundNoti = null;
11465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011466 }
11467 }
11468 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011469 } finally {
11470 Binder.restoreCallingIdentity(origId);
11471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011472 }
11473
11474 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11475 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011476 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 if (sr.isForeground) {
11478 anyForeground = true;
11479 break;
11480 }
11481 }
11482 if (anyForeground != proc.foregroundServices) {
11483 proc.foregroundServices = anyForeground;
11484 if (oomAdj) {
11485 updateOomAdjLocked();
11486 }
11487 }
11488 }
11489
11490 public int bindService(IApplicationThread caller, IBinder token,
11491 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011492 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011493 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011494 // Refuse possible leaked file descriptors
11495 if (service != null && service.hasFileDescriptors() == true) {
11496 throw new IllegalArgumentException("File descriptors passed in Intent");
11497 }
11498
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011499 checkValidCaller(Binder.getCallingUid(), userId);
11500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011501 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011502 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011503 + " type=" + resolvedType + " conn=" + connection.asBinder()
11504 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011505 if (DEBUG_MU)
11506 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11507 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011508 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11509 if (callerApp == null) {
11510 throw new SecurityException(
11511 "Unable to find app for caller " + caller
11512 + " (pid=" + Binder.getCallingPid()
11513 + ") when binding service " + service);
11514 }
11515
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011516 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011517 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011518 activity = mMainStack.isInStackLocked(token);
11519 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011520 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011521 return 0;
11522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011523 }
11524
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011525 int clientLabel = 0;
11526 PendingIntent clientIntent = null;
11527
11528 if (callerApp.info.uid == Process.SYSTEM_UID) {
11529 // Hacky kind of thing -- allow system stuff to tell us
11530 // what they are, so we can report this elsewhere for
11531 // others to know why certain services are running.
11532 try {
11533 clientIntent = (PendingIntent)service.getParcelableExtra(
11534 Intent.EXTRA_CLIENT_INTENT);
11535 } catch (RuntimeException e) {
11536 }
11537 if (clientIntent != null) {
11538 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11539 if (clientLabel != 0) {
11540 // There are no useful extras in the intent, trash them.
11541 // System code calling with this stuff just needs to know
11542 // this will happen.
11543 service = service.cloneFilter();
11544 }
11545 }
11546 }
11547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011548 ServiceLookupResult res =
11549 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011550 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 if (res == null) {
11552 return 0;
11553 }
11554 if (res.record == null) {
11555 return -1;
11556 }
11557 ServiceRecord s = res.record;
11558
11559 final long origId = Binder.clearCallingIdentity();
11560
11561 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011562 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011563 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011564 }
11565
11566 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11567 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011568 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011569
11570 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011571 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11572 if (clist == null) {
11573 clist = new ArrayList<ConnectionRecord>();
11574 s.connections.put(binder, clist);
11575 }
11576 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011577 b.connections.add(c);
11578 if (activity != null) {
11579 if (activity.connections == null) {
11580 activity.connections = new HashSet<ConnectionRecord>();
11581 }
11582 activity.connections.add(c);
11583 }
11584 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011585 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11586 b.client.hasAboveClient = true;
11587 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011588 clist = mServiceConnections.get(binder);
11589 if (clist == null) {
11590 clist = new ArrayList<ConnectionRecord>();
11591 mServiceConnections.put(binder, clist);
11592 }
11593 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594
11595 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11596 s.lastActivity = SystemClock.uptimeMillis();
11597 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11598 return 0;
11599 }
11600 }
11601
11602 if (s.app != null) {
11603 // This could have made the service more important.
11604 updateOomAdjLocked(s.app);
11605 }
11606
Joe Onorato8a9b2202010-02-26 18:56:32 -080011607 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 + ": received=" + b.intent.received
11609 + " apps=" + b.intent.apps.size()
11610 + " doRebind=" + b.intent.doRebind);
11611
11612 if (s.app != null && b.intent.received) {
11613 // Service is already running, so we can immediately
11614 // publish the connection.
11615 try {
11616 c.conn.connected(s.name, b.intent.binder);
11617 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011618 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 + " to connection " + c.conn.asBinder()
11620 + " (in " + c.binding.client.processName + ")", e);
11621 }
11622
11623 // If this is the first app connected back to this binding,
11624 // and the service had previously asked to be told when
11625 // rebound, then do so.
11626 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11627 requestServiceBindingLocked(s, b.intent, true);
11628 }
11629 } else if (!b.intent.requested) {
11630 requestServiceBindingLocked(s, b.intent, false);
11631 }
11632
11633 Binder.restoreCallingIdentity(origId);
11634 }
11635
11636 return 1;
11637 }
11638
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011639 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011640 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 IBinder binder = c.conn.asBinder();
11642 AppBindRecord b = c.binding;
11643 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011644 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11645 if (clist != null) {
11646 clist.remove(c);
11647 if (clist.size() == 0) {
11648 s.connections.remove(binder);
11649 }
11650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011651 b.connections.remove(c);
11652 if (c.activity != null && c.activity != skipAct) {
11653 if (c.activity.connections != null) {
11654 c.activity.connections.remove(c);
11655 }
11656 }
11657 if (b.client != skipApp) {
11658 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011659 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11660 b.client.updateHasAboveClientLocked();
11661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011663 clist = mServiceConnections.get(binder);
11664 if (clist != null) {
11665 clist.remove(c);
11666 if (clist.size() == 0) {
11667 mServiceConnections.remove(binder);
11668 }
11669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011670
11671 if (b.connections.size() == 0) {
11672 b.intent.apps.remove(b.client);
11673 }
11674
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011675 if (!c.serviceDead) {
11676 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11677 + ": shouldUnbind=" + b.intent.hasBound);
11678 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11679 && b.intent.hasBound) {
11680 try {
11681 bumpServiceExecutingLocked(s, "unbind");
11682 updateOomAdjLocked(s.app);
11683 b.intent.hasBound = false;
11684 // Assume the client doesn't want to know about a rebind;
11685 // we will deal with that later if it asks for one.
11686 b.intent.doRebind = false;
11687 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11688 } catch (Exception e) {
11689 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11690 serviceDoneExecutingLocked(s, true);
11691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011692 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011693
11694 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11695 bringDownServiceLocked(s, false);
11696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011697 }
11698 }
11699
11700 public boolean unbindService(IServiceConnection connection) {
11701 synchronized (this) {
11702 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011703 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011704 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11705 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011706 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011707 + connection.asBinder());
11708 return false;
11709 }
11710
11711 final long origId = Binder.clearCallingIdentity();
11712
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011713 while (clist.size() > 0) {
11714 ConnectionRecord r = clist.get(0);
11715 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011717 if (r.binding.service.app != null) {
11718 // This could have made the service less important.
11719 updateOomAdjLocked(r.binding.service.app);
11720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 }
11722
11723 Binder.restoreCallingIdentity(origId);
11724 }
11725
11726 return true;
11727 }
11728
11729 public void publishService(IBinder token, Intent intent, IBinder service) {
11730 // Refuse possible leaked file descriptors
11731 if (intent != null && intent.hasFileDescriptors() == true) {
11732 throw new IllegalArgumentException("File descriptors passed in Intent");
11733 }
11734
11735 synchronized(this) {
11736 if (!(token instanceof ServiceRecord)) {
11737 throw new IllegalArgumentException("Invalid service token");
11738 }
11739 ServiceRecord r = (ServiceRecord)token;
11740
11741 final long origId = Binder.clearCallingIdentity();
11742
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011743 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 + " " + intent + ": " + service);
11745 if (r != null) {
11746 Intent.FilterComparison filter
11747 = new Intent.FilterComparison(intent);
11748 IntentBindRecord b = r.bindings.get(filter);
11749 if (b != null && !b.received) {
11750 b.binder = service;
11751 b.requested = true;
11752 b.received = true;
11753 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011754 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011755 = r.connections.values().iterator();
11756 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011757 ArrayList<ConnectionRecord> clist = it.next();
11758 for (int i=0; i<clist.size(); i++) {
11759 ConnectionRecord c = clist.get(i);
11760 if (!filter.equals(c.binding.intent.intent)) {
11761 if (DEBUG_SERVICE) Slog.v(
11762 TAG, "Not publishing to: " + c);
11763 if (DEBUG_SERVICE) Slog.v(
11764 TAG, "Bound intent: " + c.binding.intent.intent);
11765 if (DEBUG_SERVICE) Slog.v(
11766 TAG, "Published intent: " + intent);
11767 continue;
11768 }
11769 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11770 try {
11771 c.conn.connected(r.name, service);
11772 } catch (Exception e) {
11773 Slog.w(TAG, "Failure sending service " + r.name +
11774 " to connection " + c.conn.asBinder() +
11775 " (in " + c.binding.client.processName + ")", e);
11776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777 }
11778 }
11779 }
11780 }
11781
11782 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11783
11784 Binder.restoreCallingIdentity(origId);
11785 }
11786 }
11787 }
11788
11789 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11790 // Refuse possible leaked file descriptors
11791 if (intent != null && intent.hasFileDescriptors() == true) {
11792 throw new IllegalArgumentException("File descriptors passed in Intent");
11793 }
11794
11795 synchronized(this) {
11796 if (!(token instanceof ServiceRecord)) {
11797 throw new IllegalArgumentException("Invalid service token");
11798 }
11799 ServiceRecord r = (ServiceRecord)token;
11800
11801 final long origId = Binder.clearCallingIdentity();
11802
11803 if (r != null) {
11804 Intent.FilterComparison filter
11805 = new Intent.FilterComparison(intent);
11806 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011807 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 + " at " + b + ": apps="
11809 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011810
11811 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011813 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 // Applications have already bound since the last
11815 // unbind, so just rebind right here.
11816 requestServiceBindingLocked(r, b, true);
11817 } else {
11818 // Note to tell the service the next time there is
11819 // a new client.
11820 b.doRebind = true;
11821 }
11822 }
11823
Per Edelberg78f9fff2010-08-30 20:01:35 +020011824 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011825
11826 Binder.restoreCallingIdentity(origId);
11827 }
11828 }
11829 }
11830
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011831 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 synchronized(this) {
11833 if (!(token instanceof ServiceRecord)) {
11834 throw new IllegalArgumentException("Invalid service token");
11835 }
11836 ServiceRecord r = (ServiceRecord)token;
11837 boolean inStopping = mStoppingServices.contains(token);
11838 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011840 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011841 + " with incorrect token: given " + token
11842 + ", expected " + r);
11843 return;
11844 }
11845
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011846 if (type == 1) {
11847 // This is a call from a service start... take care of
11848 // book-keeping.
11849 r.callStart = true;
11850 switch (res) {
11851 case Service.START_STICKY_COMPATIBILITY:
11852 case Service.START_STICKY: {
11853 // We are done with the associated start arguments.
11854 r.findDeliveredStart(startId, true);
11855 // Don't stop if killed.
11856 r.stopIfKilled = false;
11857 break;
11858 }
11859 case Service.START_NOT_STICKY: {
11860 // We are done with the associated start arguments.
11861 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011862 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011863 // There is no more work, and this service
11864 // doesn't want to hang around if killed.
11865 r.stopIfKilled = true;
11866 }
11867 break;
11868 }
11869 case Service.START_REDELIVER_INTENT: {
11870 // We'll keep this item until they explicitly
11871 // call stop for it, but keep track of the fact
11872 // that it was delivered.
11873 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11874 if (si != null) {
11875 si.deliveryCount = 0;
11876 si.doneExecutingCount++;
11877 // Don't stop if killed.
11878 r.stopIfKilled = true;
11879 }
11880 break;
11881 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011882 case Service.START_TASK_REMOVED_COMPLETE: {
11883 // Special processing for onTaskRemoved(). Don't
11884 // impact normal onStartCommand() processing.
11885 r.findDeliveredStart(startId, true);
11886 break;
11887 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011888 default:
11889 throw new IllegalArgumentException(
11890 "Unknown service start result: " + res);
11891 }
11892 if (res == Service.START_STICKY_COMPATIBILITY) {
11893 r.callStart = false;
11894 }
11895 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011896 if (DEBUG_MU)
11897 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11898 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011899 final long origId = Binder.clearCallingIdentity();
11900 serviceDoneExecutingLocked(r, inStopping);
11901 Binder.restoreCallingIdentity(origId);
11902 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011903 Slog.w(TAG, "Done executing unknown service from pid "
11904 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011905 }
11906 }
11907 }
11908
11909 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011910 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11911 + ": nesting=" + r.executeNesting
11912 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011913 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011914 r.executeNesting--;
11915 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011916 if (DEBUG_SERVICE) Slog.v(TAG,
11917 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011918 r.app.executingServices.remove(r);
11919 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011920 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11921 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11923 }
11924 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011925 if (DEBUG_SERVICE) Slog.v(TAG,
11926 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011927 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011928 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011929 }
11930 updateOomAdjLocked(r.app);
11931 }
11932 }
11933
11934 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011935 String anrMessage = null;
11936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 synchronized(this) {
11938 if (proc.executingServices.size() == 0 || proc.thread == null) {
11939 return;
11940 }
11941 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11942 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11943 ServiceRecord timeout = null;
11944 long nextTime = 0;
11945 while (it.hasNext()) {
11946 ServiceRecord sr = it.next();
11947 if (sr.executingStart < maxTime) {
11948 timeout = sr;
11949 break;
11950 }
11951 if (sr.executingStart > nextTime) {
11952 nextTime = sr.executingStart;
11953 }
11954 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011955 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011956 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011957 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011958 } else {
11959 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11960 msg.obj = proc;
11961 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11962 }
11963 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011964
11965 if (anrMessage != null) {
11966 appNotResponding(proc, null, null, anrMessage);
11967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011968 }
11969
11970 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011971 // BACKUP AND RESTORE
11972 // =========================================================
11973
11974 // Cause the target app to be launched if necessary and its backup agent
11975 // instantiated. The backup agent will invoke backupAgentCreated() on the
11976 // activity manager to announce its creation.
11977 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011978 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011979 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11980
11981 synchronized(this) {
11982 // !!! TODO: currently no check here that we're already bound
11983 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11984 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11985 synchronized (stats) {
11986 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11987 }
11988
Dianne Hackborne7f97212011-02-24 14:40:20 -080011989 // Backup agent is now in use, its package can't be stopped.
11990 try {
11991 AppGlobals.getPackageManager().setPackageStoppedState(
11992 app.packageName, false);
11993 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011994 } catch (IllegalArgumentException e) {
11995 Slog.w(TAG, "Failed trying to unstop package "
11996 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011997 }
11998
Christopher Tate181fafa2009-05-14 11:12:14 -070011999 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012000 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12001 ? new ComponentName(app.packageName, app.backupAgentName)
12002 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012003 // startProcessLocked() returns existing proc's record if it's already running
12004 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012005 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012006 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012007 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012008 return false;
12009 }
12010
12011 r.app = proc;
12012 mBackupTarget = r;
12013 mBackupAppName = app.packageName;
12014
Christopher Tate6fa95972009-06-05 18:43:55 -070012015 // Try not to kill the process during backup
12016 updateOomAdjLocked(proc);
12017
Christopher Tate181fafa2009-05-14 11:12:14 -070012018 // If the process is already attached, schedule the creation of the backup agent now.
12019 // If it is not yet live, this will be done when it attaches to the framework.
12020 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012021 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012022 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012023 proc.thread.scheduleCreateBackupAgent(app,
12024 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012025 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012026 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012027 }
12028 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012029 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012030 }
12031 // Invariants: at this point, the target app process exists and the application
12032 // is either already running or in the process of coming up. mBackupTarget and
12033 // mBackupAppName describe the app, so that when it binds back to the AM we
12034 // know that it's scheduled for a backup-agent operation.
12035 }
12036
12037 return true;
12038 }
12039
12040 // A backup agent has just come up
12041 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012042 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012043 + " = " + agent);
12044
12045 synchronized(this) {
12046 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012047 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012048 return;
12049 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012050 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012051
Dianne Hackborn06740692010-09-22 22:46:21 -070012052 long oldIdent = Binder.clearCallingIdentity();
12053 try {
12054 IBackupManager bm = IBackupManager.Stub.asInterface(
12055 ServiceManager.getService(Context.BACKUP_SERVICE));
12056 bm.agentConnected(agentPackageName, agent);
12057 } catch (RemoteException e) {
12058 // can't happen; the backup manager service is local
12059 } catch (Exception e) {
12060 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12061 e.printStackTrace();
12062 } finally {
12063 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012064 }
12065 }
12066
12067 // done with this agent
12068 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012069 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012070 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012071 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012072 return;
12073 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012074
12075 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012076 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012077 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012078 return;
12079 }
12080
Christopher Tate181fafa2009-05-14 11:12:14 -070012081 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012082 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012083 return;
12084 }
12085
Christopher Tate6fa95972009-06-05 18:43:55 -070012086 ProcessRecord proc = mBackupTarget.app;
12087 mBackupTarget = null;
12088 mBackupAppName = null;
12089
12090 // Not backing this app up any more; reset its OOM adjustment
12091 updateOomAdjLocked(proc);
12092
Christopher Tatec7b31e32009-06-10 15:49:30 -070012093 // If the app crashed during backup, 'thread' will be null here
12094 if (proc.thread != null) {
12095 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012096 proc.thread.scheduleDestroyBackupAgent(appInfo,
12097 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012098 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012099 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012100 e.printStackTrace();
12101 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012102 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012103 }
12104 }
12105 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106 // BROADCASTS
12107 // =========================================================
12108
Josh Bartel7f208742010-02-25 11:01:44 -060012109 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012110 List cur) {
12111 final ContentResolver resolver = mContext.getContentResolver();
12112 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12113 if (list == null) {
12114 return cur;
12115 }
12116 int N = list.size();
12117 for (int i=0; i<N; i++) {
12118 Intent intent = list.get(i);
12119 if (filter.match(resolver, intent, true, TAG) >= 0) {
12120 if (cur == null) {
12121 cur = new ArrayList<Intent>();
12122 }
12123 cur.add(intent);
12124 }
12125 }
12126 return cur;
12127 }
12128
Christopher Tatef46723b2012-01-26 14:19:24 -080012129 boolean isPendingBroadcastProcessLocked(int pid) {
12130 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12131 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133
Christopher Tatef46723b2012-01-26 14:19:24 -080012134 void skipPendingBroadcastLocked(int pid) {
12135 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12136 for (BroadcastQueue queue : mBroadcastQueues) {
12137 queue.skipPendingBroadcastLocked(pid);
12138 }
12139 }
12140
12141 // The app just attached; send any pending broadcasts that it should receive
12142 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12143 boolean didSomething = false;
12144 for (BroadcastQueue queue : mBroadcastQueues) {
12145 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012147 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012148 }
12149
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012150 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012151 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012152 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012153 synchronized(this) {
12154 ProcessRecord callerApp = null;
12155 if (caller != null) {
12156 callerApp = getRecordForAppLocked(caller);
12157 if (callerApp == null) {
12158 throw new SecurityException(
12159 "Unable to find app for caller " + caller
12160 + " (pid=" + Binder.getCallingPid()
12161 + ") when registering receiver " + receiver);
12162 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012163 if (callerApp.info.uid != Process.SYSTEM_UID &&
12164 !callerApp.pkgList.contains(callerPackage)) {
12165 throw new SecurityException("Given caller package " + callerPackage
12166 + " is not running in process " + callerApp);
12167 }
12168 } else {
12169 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012170 }
12171
12172 List allSticky = null;
12173
12174 // Look for any matching sticky broadcasts...
12175 Iterator actions = filter.actionsIterator();
12176 if (actions != null) {
12177 while (actions.hasNext()) {
12178 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012179 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012180 }
12181 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012182 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 }
12184
12185 // The first sticky in the list is returned directly back to
12186 // the client.
12187 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12188
Joe Onorato8a9b2202010-02-26 18:56:32 -080012189 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012190 + ": " + sticky);
12191
12192 if (receiver == null) {
12193 return sticky;
12194 }
12195
12196 ReceiverList rl
12197 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12198 if (rl == null) {
12199 rl = new ReceiverList(this, callerApp,
12200 Binder.getCallingPid(),
12201 Binder.getCallingUid(), receiver);
12202 if (rl.app != null) {
12203 rl.app.receivers.add(rl);
12204 } else {
12205 try {
12206 receiver.asBinder().linkToDeath(rl, 0);
12207 } catch (RemoteException e) {
12208 return sticky;
12209 }
12210 rl.linkedToDeath = true;
12211 }
12212 mRegisteredReceivers.put(receiver.asBinder(), rl);
12213 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012214 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 rl.add(bf);
12216 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012217 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 }
12219 mReceiverResolver.addFilter(bf);
12220
12221 // Enqueue broadcasts for all existing stickies that match
12222 // this filter.
12223 if (allSticky != null) {
12224 ArrayList receivers = new ArrayList();
12225 receivers.add(bf);
12226
12227 int N = allSticky.size();
12228 for (int i=0; i<N; i++) {
12229 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012230 BroadcastQueue queue = broadcastQueueForIntent(intent);
12231 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012232 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012233 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012234 queue.enqueueParallelBroadcastLocked(r);
12235 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 }
12237 }
12238
12239 return sticky;
12240 }
12241 }
12242
12243 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012244 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245
Christopher Tatef46723b2012-01-26 14:19:24 -080012246 final long origId = Binder.clearCallingIdentity();
12247 try {
12248 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249
Christopher Tatef46723b2012-01-26 14:19:24 -080012250 synchronized(this) {
12251 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012252 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012253 if (rl != null) {
12254 if (rl.curBroadcast != null) {
12255 BroadcastRecord r = rl.curBroadcast;
12256 final boolean doNext = finishReceiverLocked(
12257 receiver.asBinder(), r.resultCode, r.resultData,
12258 r.resultExtras, r.resultAbort, true);
12259 if (doNext) {
12260 doTrim = true;
12261 r.queue.processNextBroadcast(false);
12262 }
12263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012264
Christopher Tatef46723b2012-01-26 14:19:24 -080012265 if (rl.app != null) {
12266 rl.app.receivers.remove(rl);
12267 }
12268 removeReceiverLocked(rl);
12269 if (rl.linkedToDeath) {
12270 rl.linkedToDeath = false;
12271 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012273 }
12274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012275
Christopher Tatef46723b2012-01-26 14:19:24 -080012276 // If we actually concluded any broadcasts, we might now be able
12277 // to trim the recipients' apps from our working set
12278 if (doTrim) {
12279 trimApplications();
12280 return;
12281 }
12282
12283 } finally {
12284 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012286 }
12287
12288 void removeReceiverLocked(ReceiverList rl) {
12289 mRegisteredReceivers.remove(rl.receiver.asBinder());
12290 int N = rl.size();
12291 for (int i=0; i<N; i++) {
12292 mReceiverResolver.removeFilter(rl.get(i));
12293 }
12294 }
12295
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012296 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12297 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12298 ProcessRecord r = mLruProcesses.get(i);
12299 if (r.thread != null) {
12300 try {
12301 r.thread.dispatchPackageBroadcast(cmd, packages);
12302 } catch (RemoteException ex) {
12303 }
12304 }
12305 }
12306 }
12307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012308 private final int broadcastIntentLocked(ProcessRecord callerApp,
12309 String callerPackage, Intent intent, String resolvedType,
12310 IIntentReceiver resultTo, int resultCode, String resultData,
12311 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012312 boolean ordered, boolean sticky, int callingPid, int callingUid,
12313 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012314 intent = new Intent(intent);
12315
Dianne Hackborne7f97212011-02-24 14:40:20 -080012316 // By default broadcasts do not go to stopped apps.
12317 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12318
Joe Onorato8a9b2202010-02-26 18:56:32 -080012319 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12321 + " ordered=" + ordered);
12322 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012323 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012324 }
12325
12326 // Handle special intents: if this broadcast is from the package
12327 // manager about a package being removed, we need to remove all of
12328 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012329 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012331 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12332 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012333 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012334 || uidRemoved) {
12335 if (checkComponentPermission(
12336 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012337 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012338 == PackageManager.PERMISSION_GRANTED) {
12339 if (uidRemoved) {
12340 final Bundle intentExtras = intent.getExtras();
12341 final int uid = intentExtras != null
12342 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12343 if (uid >= 0) {
12344 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12345 synchronized (bs) {
12346 bs.removeUidStatsLocked(uid);
12347 }
12348 }
12349 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012350 // If resources are unvailble just force stop all
12351 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012352 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012353 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12354 if (list != null && (list.length > 0)) {
12355 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012356 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012357 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012358 sendPackageBroadcastLocked(
12359 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012360 }
12361 } else {
12362 Uri data = intent.getData();
12363 String ssp;
12364 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12365 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12366 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012367 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012368 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012369 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012370 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12371 new String[] {ssp});
12372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373 }
12374 }
12375 }
12376 } else {
12377 String msg = "Permission Denial: " + intent.getAction()
12378 + " broadcast from " + callerPackage + " (pid=" + callingPid
12379 + ", uid=" + callingUid + ")"
12380 + " requires "
12381 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012382 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 throw new SecurityException(msg);
12384 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012385
12386 // Special case for adding a package: by default turn on compatibility
12387 // mode.
12388 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012389 Uri data = intent.getData();
12390 String ssp;
12391 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12392 mCompatModePackages.handlePackageAddedLocked(ssp,
12393 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012395 }
12396
12397 /*
12398 * If this is the time zone changed action, queue up a message that will reset the timezone
12399 * of all currently running processes. This message will get queued up before the broadcast
12400 * happens.
12401 */
12402 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12403 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12404 }
12405
Robert Greenwalt03595d02010-11-02 14:08:23 -070012406 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12407 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12408 }
12409
Robert Greenwalt434203a2010-10-11 16:00:27 -070012410 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12411 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12412 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12413 }
12414
Dianne Hackborn854060af2009-07-09 18:14:31 -070012415 /*
12416 * Prevent non-system code (defined here to be non-persistent
12417 * processes) from sending protected broadcasts.
12418 */
12419 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12420 || callingUid == Process.SHELL_UID || callingUid == 0) {
12421 // Always okay.
12422 } else if (callerApp == null || !callerApp.persistent) {
12423 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012424 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012425 intent.getAction())) {
12426 String msg = "Permission Denial: not allowed to send broadcast "
12427 + intent.getAction() + " from pid="
12428 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012429 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012430 throw new SecurityException(msg);
12431 }
12432 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012433 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012434 return BROADCAST_SUCCESS;
12435 }
12436 }
12437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012438 // Add to the sticky list if requested.
12439 if (sticky) {
12440 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12441 callingPid, callingUid)
12442 != PackageManager.PERMISSION_GRANTED) {
12443 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12444 + callingPid + ", uid=" + callingUid
12445 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012446 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012447 throw new SecurityException(msg);
12448 }
12449 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012450 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 + " and enforce permission " + requiredPermission);
12452 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12453 }
12454 if (intent.getComponent() != null) {
12455 throw new SecurityException(
12456 "Sticky broadcasts can't target a specific component");
12457 }
12458 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12459 if (list == null) {
12460 list = new ArrayList<Intent>();
12461 mStickyBroadcasts.put(intent.getAction(), list);
12462 }
12463 int N = list.size();
12464 int i;
12465 for (i=0; i<N; i++) {
12466 if (intent.filterEquals(list.get(i))) {
12467 // This sticky already exists, replace it.
12468 list.set(i, new Intent(intent));
12469 break;
12470 }
12471 }
12472 if (i >= N) {
12473 list.add(new Intent(intent));
12474 }
12475 }
12476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 // Figure out who all will receive this broadcast.
12478 List receivers = null;
12479 List<BroadcastFilter> registeredReceivers = null;
12480 try {
12481 if (intent.getComponent() != null) {
12482 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012483 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012484 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012485 if (ai != null) {
12486 receivers = new ArrayList();
12487 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012488 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 receivers.add(ri);
12490 }
12491 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012492 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012493 // Need to resolve the intent to interested receivers...
12494 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12495 == 0) {
12496 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012497 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012498 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 }
Mihai Preda074edef2009-05-18 17:13:31 +020012500 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012501 }
12502 } catch (RemoteException ex) {
12503 // pm is in same process, this will never happen.
12504 }
12505
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012506 final boolean replacePending =
12507 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12508
Joe Onorato8a9b2202010-02-26 18:56:32 -080012509 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012510 + " replacePending=" + replacePending);
12511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012512 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12513 if (!ordered && NR > 0) {
12514 // If we are not serializing this broadcast, then send the
12515 // registered receivers separately so they don't wait for the
12516 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012517 final 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,
12520 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012521 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012522 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012523 TAG, "Enqueueing parallel broadcast " + r);
12524 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012525 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012526 queue.enqueueParallelBroadcastLocked(r);
12527 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529 registeredReceivers = null;
12530 NR = 0;
12531 }
12532
12533 // Merge into one list.
12534 int ir = 0;
12535 if (receivers != null) {
12536 // A special case for PACKAGE_ADDED: do not allow the package
12537 // being added to see this broadcast. This prevents them from
12538 // using this as a back door to get run as soon as they are
12539 // installed. Maybe in the future we want to have a special install
12540 // broadcast or such for apps, but we'd like to deliberately make
12541 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012542 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012543 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12544 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12545 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012546 Uri data = intent.getData();
12547 if (data != null) {
12548 String pkgName = data.getSchemeSpecificPart();
12549 if (pkgName != null) {
12550 skipPackages = new String[] { pkgName };
12551 }
12552 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012553 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012554 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012555 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012556 if (skipPackages != null && (skipPackages.length > 0)) {
12557 for (String skipPackage : skipPackages) {
12558 if (skipPackage != null) {
12559 int NT = receivers.size();
12560 for (int it=0; it<NT; it++) {
12561 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12562 if (curt.activityInfo.packageName.equals(skipPackage)) {
12563 receivers.remove(it);
12564 it--;
12565 NT--;
12566 }
12567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012568 }
12569 }
12570 }
12571
12572 int NT = receivers != null ? receivers.size() : 0;
12573 int it = 0;
12574 ResolveInfo curt = null;
12575 BroadcastFilter curr = null;
12576 while (it < NT && ir < NR) {
12577 if (curt == null) {
12578 curt = (ResolveInfo)receivers.get(it);
12579 }
12580 if (curr == null) {
12581 curr = registeredReceivers.get(ir);
12582 }
12583 if (curr.getPriority() >= curt.priority) {
12584 // Insert this broadcast record into the final list.
12585 receivers.add(it, curr);
12586 ir++;
12587 curr = null;
12588 it++;
12589 NT++;
12590 } else {
12591 // Skip to the next ResolveInfo in the final list.
12592 it++;
12593 curt = null;
12594 }
12595 }
12596 }
12597 while (ir < NR) {
12598 if (receivers == null) {
12599 receivers = new ArrayList();
12600 }
12601 receivers.add(registeredReceivers.get(ir));
12602 ir++;
12603 }
12604
12605 if ((receivers != null && receivers.size() > 0)
12606 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012607 BroadcastQueue queue = broadcastQueueForIntent(intent);
12608 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012610 receivers, resultTo, resultCode, resultData, map, ordered,
12611 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012612 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012613 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012614 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 if (DEBUG_BROADCAST) {
12616 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012617 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012619 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012620 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012621 queue.enqueueOrderedBroadcastLocked(r);
12622 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012624 }
12625
12626 return BROADCAST_SUCCESS;
12627 }
12628
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012629 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012630 // Refuse possible leaked file descriptors
12631 if (intent != null && intent.hasFileDescriptors() == true) {
12632 throw new IllegalArgumentException("File descriptors passed in Intent");
12633 }
12634
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012635 int flags = intent.getFlags();
12636
12637 if (!mProcessesReady) {
12638 // if the caller really truly claims to know what they're doing, go
12639 // ahead and allow the broadcast without launching any receivers
12640 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12641 intent = new Intent(intent);
12642 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12643 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12644 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12645 + " before boot completion");
12646 throw new IllegalStateException("Cannot broadcast before boot completed");
12647 }
12648 }
12649
12650 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12651 throw new IllegalArgumentException(
12652 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12653 }
12654
12655 return intent;
12656 }
12657
12658 public final int broadcastIntent(IApplicationThread caller,
12659 Intent intent, String resolvedType, IIntentReceiver resultTo,
12660 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012661 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012662 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012664 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012666 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12667 final int callingPid = Binder.getCallingPid();
12668 final int callingUid = Binder.getCallingUid();
12669 final long origId = Binder.clearCallingIdentity();
12670 int res = broadcastIntentLocked(callerApp,
12671 callerApp != null ? callerApp.info.packageName : null,
12672 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012673 resultCode, resultData, map, requiredPermission, serialized, sticky,
12674 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012675 Binder.restoreCallingIdentity(origId);
12676 return res;
12677 }
12678 }
12679
12680 int broadcastIntentInPackage(String packageName, int uid,
12681 Intent intent, String resolvedType, IIntentReceiver resultTo,
12682 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012683 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012685 intent = verifyBroadcastLocked(intent);
12686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 final long origId = Binder.clearCallingIdentity();
12688 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12689 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012690 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 Binder.restoreCallingIdentity(origId);
12692 return res;
12693 }
12694 }
12695
Amith Yamasani742a6712011-05-04 14:49:28 -070012696 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12697 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012698 // Refuse possible leaked file descriptors
12699 if (intent != null && intent.hasFileDescriptors() == true) {
12700 throw new IllegalArgumentException("File descriptors passed in Intent");
12701 }
12702
12703 synchronized(this) {
12704 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12705 != PackageManager.PERMISSION_GRANTED) {
12706 String msg = "Permission Denial: unbroadcastIntent() from pid="
12707 + Binder.getCallingPid()
12708 + ", uid=" + Binder.getCallingUid()
12709 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012710 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012711 throw new SecurityException(msg);
12712 }
12713 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12714 if (list != null) {
12715 int N = list.size();
12716 int i;
12717 for (i=0; i<N; i++) {
12718 if (intent.filterEquals(list.get(i))) {
12719 list.remove(i);
12720 break;
12721 }
12722 }
12723 }
12724 }
12725 }
12726
12727 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12728 String resultData, Bundle resultExtras, boolean resultAbort,
12729 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012730 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12731 if (r == null) {
12732 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 return false;
12734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735
Christopher Tatef46723b2012-01-26 14:19:24 -080012736 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12737 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012738 }
12739
12740 public void finishReceiver(IBinder who, int resultCode, String resultData,
12741 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012742 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012743
12744 // Refuse possible leaked file descriptors
12745 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12746 throw new IllegalArgumentException("File descriptors passed in Bundle");
12747 }
12748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012749 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012750 try {
12751 boolean doNext = false;
12752 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012753
Christopher Tatef46723b2012-01-26 14:19:24 -080012754 synchronized(this) {
12755 r = broadcastRecordForReceiverLocked(who);
12756 if (r != null) {
12757 doNext = r.queue.finishReceiverLocked(r, resultCode,
12758 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012760 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012761
Christopher Tatef46723b2012-01-26 14:19:24 -080012762 if (doNext) {
12763 r.queue.processNextBroadcast(false);
12764 }
12765 trimApplications();
12766 } finally {
12767 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012771 // =========================================================
12772 // INSTRUMENTATION
12773 // =========================================================
12774
12775 public boolean startInstrumentation(ComponentName className,
12776 String profileFile, int flags, Bundle arguments,
12777 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012778 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779 // Refuse possible leaked file descriptors
12780 if (arguments != null && arguments.hasFileDescriptors()) {
12781 throw new IllegalArgumentException("File descriptors passed in Bundle");
12782 }
12783
12784 synchronized(this) {
12785 InstrumentationInfo ii = null;
12786 ApplicationInfo ai = null;
12787 try {
12788 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012789 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012790 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012791 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012792 } catch (PackageManager.NameNotFoundException e) {
12793 }
12794 if (ii == null) {
12795 reportStartInstrumentationFailure(watcher, className,
12796 "Unable to find instrumentation info for: " + className);
12797 return false;
12798 }
12799 if (ai == null) {
12800 reportStartInstrumentationFailure(watcher, className,
12801 "Unable to find instrumentation target package: " + ii.targetPackage);
12802 return false;
12803 }
12804
12805 int match = mContext.getPackageManager().checkSignatures(
12806 ii.targetPackage, ii.packageName);
12807 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12808 String msg = "Permission Denial: starting instrumentation "
12809 + className + " from pid="
12810 + Binder.getCallingPid()
12811 + ", uid=" + Binder.getCallingPid()
12812 + " not allowed because package " + ii.packageName
12813 + " does not have a signature matching the target "
12814 + ii.targetPackage;
12815 reportStartInstrumentationFailure(watcher, className, msg);
12816 throw new SecurityException(msg);
12817 }
12818
12819 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012820 // Instrumentation can kill and relaunch even persistent processes
12821 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012822 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012824 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012825 app.instrumentationProfileFile = profileFile;
12826 app.instrumentationArguments = arguments;
12827 app.instrumentationWatcher = watcher;
12828 app.instrumentationResultClass = className;
12829 Binder.restoreCallingIdentity(origId);
12830 }
12831
12832 return true;
12833 }
12834
12835 /**
12836 * Report errors that occur while attempting to start Instrumentation. Always writes the
12837 * error to the logs, but if somebody is watching, send the report there too. This enables
12838 * the "am" command to report errors with more information.
12839 *
12840 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12841 * @param cn The component name of the instrumentation.
12842 * @param report The error report.
12843 */
12844 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12845 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012846 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012847 try {
12848 if (watcher != null) {
12849 Bundle results = new Bundle();
12850 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12851 results.putString("Error", report);
12852 watcher.instrumentationStatus(cn, -1, results);
12853 }
12854 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012855 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012856 }
12857 }
12858
12859 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12860 if (app.instrumentationWatcher != null) {
12861 try {
12862 // NOTE: IInstrumentationWatcher *must* be oneway here
12863 app.instrumentationWatcher.instrumentationFinished(
12864 app.instrumentationClass,
12865 resultCode,
12866 results);
12867 } catch (RemoteException e) {
12868 }
12869 }
12870 app.instrumentationWatcher = null;
12871 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012872 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012873 app.instrumentationProfileFile = null;
12874 app.instrumentationArguments = null;
12875
Christopher Tate3dacd842011-08-19 14:56:15 -070012876 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012877 }
12878
12879 public void finishInstrumentation(IApplicationThread target,
12880 int resultCode, Bundle results) {
12881 // Refuse possible leaked file descriptors
12882 if (results != null && results.hasFileDescriptors()) {
12883 throw new IllegalArgumentException("File descriptors passed in Intent");
12884 }
12885
12886 synchronized(this) {
12887 ProcessRecord app = getRecordForAppLocked(target);
12888 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012889 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012890 return;
12891 }
12892 final long origId = Binder.clearCallingIdentity();
12893 finishInstrumentationLocked(app, resultCode, results);
12894 Binder.restoreCallingIdentity(origId);
12895 }
12896 }
12897
12898 // =========================================================
12899 // CONFIGURATION
12900 // =========================================================
12901
12902 public ConfigurationInfo getDeviceConfigurationInfo() {
12903 ConfigurationInfo config = new ConfigurationInfo();
12904 synchronized (this) {
12905 config.reqTouchScreen = mConfiguration.touchscreen;
12906 config.reqKeyboardType = mConfiguration.keyboard;
12907 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012908 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12909 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012910 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12911 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012912 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12913 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012914 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12915 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012916 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012917 }
12918 return config;
12919 }
12920
12921 public Configuration getConfiguration() {
12922 Configuration ci;
12923 synchronized(this) {
12924 ci = new Configuration(mConfiguration);
12925 }
12926 return ci;
12927 }
12928
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012929 public void updatePersistentConfiguration(Configuration values) {
12930 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12931 "updateConfiguration()");
12932 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12933 "updateConfiguration()");
12934 if (values == null) {
12935 throw new NullPointerException("Configuration must not be null");
12936 }
12937
12938 synchronized(this) {
12939 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012940 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012941 Binder.restoreCallingIdentity(origId);
12942 }
12943 }
12944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012945 public void updateConfiguration(Configuration values) {
12946 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12947 "updateConfiguration()");
12948
12949 synchronized(this) {
12950 if (values == null && mWindowManager != null) {
12951 // sentinel: fetch the current configuration from the window manager
12952 values = mWindowManager.computeNewConfiguration();
12953 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012954
12955 if (mWindowManager != null) {
12956 mProcessList.applyDisplaySize(mWindowManager);
12957 }
12958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012960 if (values != null) {
12961 Settings.System.clearConfiguration(values);
12962 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012963 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 Binder.restoreCallingIdentity(origId);
12965 }
12966 }
12967
12968 /**
12969 * Do either or both things: (1) change the current configuration, and (2)
12970 * make sure the given activity is running with the (now) current
12971 * configuration. Returns true if the activity has been left running, or
12972 * false if <var>starting</var> is being destroyed to match the new
12973 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012974 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012976 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012977 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012978 // do nothing if we are headless
12979 if (mHeadless) return true;
12980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012981 int changes = 0;
12982
12983 boolean kept = true;
12984
12985 if (values != null) {
12986 Configuration newConfig = new Configuration(mConfiguration);
12987 changes = newConfig.updateFrom(values);
12988 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012989 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012990 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012991 }
12992
Doug Zongker2bec3d42009-12-04 12:52:44 -080012993 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994
Dianne Hackborn813075a62011-11-14 17:45:19 -080012995 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012996 saveLocaleLocked(values.locale,
12997 !values.locale.equals(mConfiguration.locale),
12998 values.userSetLocale);
12999 }
13000
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013001 mConfigurationSeq++;
13002 if (mConfigurationSeq <= 0) {
13003 mConfigurationSeq = 1;
13004 }
13005 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013006 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013007 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013008
13009 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013010
13011 // TODO: If our config changes, should we auto dismiss any currently
13012 // showing dialogs?
13013 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013014
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013015 AttributeCache ac = AttributeCache.instance();
13016 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013017 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013020 // Make sure all resources in our process are updated
13021 // right now, so that anyone who is going to retrieve
13022 // resource values after we return will be sure to get
13023 // the new ones. This is especially important during
13024 // boot, where the first config change needs to guarantee
13025 // all resources have that config before following boot
13026 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013027 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013028
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013029 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013030 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013031 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013032 mHandler.sendMessage(msg);
13033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013034
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013035 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13036 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013037 try {
13038 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013039 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013040 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013041 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013042 }
13043 } catch (Exception e) {
13044 }
13045 }
13046 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013047 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13048 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013049 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013050 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013051 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13052 broadcastIntentLocked(null, null,
13053 new Intent(Intent.ACTION_LOCALE_CHANGED),
13054 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013055 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013057 }
13058 }
13059
13060 if (changes != 0 && starting == null) {
13061 // If the configuration changed, and the caller is not already
13062 // in the process of starting an activity, then find the top
13063 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013064 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065 }
13066
13067 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013068 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013069 // And we need to make sure at this point that all other activities
13070 // are made visible with the correct configuration.
13071 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072 }
13073
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013074 if (values != null && mWindowManager != null) {
13075 mWindowManager.setNewConfiguration(mConfiguration);
13076 }
13077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078 return kept;
13079 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013080
13081 /**
13082 * Decide based on the configuration whether we should shouw the ANR,
13083 * crash, etc dialogs. The idea is that if there is no affordnace to
13084 * press the on-screen buttons, we shouldn't show the dialog.
13085 *
13086 * A thought: SystemUI might also want to get told about this, the Power
13087 * dialog / global actions also might want different behaviors.
13088 */
13089 private static final boolean shouldShowDialogs(Configuration config) {
13090 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13091 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013093
13094 /**
13095 * Save the locale. You must be inside a synchronized (this) block.
13096 */
13097 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13098 if(isDiff) {
13099 SystemProperties.set("user.language", l.getLanguage());
13100 SystemProperties.set("user.region", l.getCountry());
13101 }
13102
13103 if(isPersist) {
13104 SystemProperties.set("persist.sys.language", l.getLanguage());
13105 SystemProperties.set("persist.sys.country", l.getCountry());
13106 SystemProperties.set("persist.sys.localevar", l.getVariant());
13107 }
13108 }
13109
13110 // =========================================================
13111 // LIFETIME MANAGEMENT
13112 // =========================================================
13113
Christopher Tatef46723b2012-01-26 14:19:24 -080013114 // Returns which broadcast queue the app is the current [or imminent] receiver
13115 // on, or 'null' if the app is not an active broadcast recipient.
13116 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13117 BroadcastRecord r = app.curReceiver;
13118 if (r != null) {
13119 return r.queue;
13120 }
13121
13122 // It's not the current receiver, but it might be starting up to become one
13123 synchronized (this) {
13124 for (BroadcastQueue queue : mBroadcastQueues) {
13125 r = queue.mPendingBroadcast;
13126 if (r != null && r.curApp == app) {
13127 // found it; report which queue it's in
13128 return queue;
13129 }
13130 }
13131 }
13132
13133 return null;
13134 }
13135
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013136 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013137 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013138 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013139 // This adjustment has already been computed. If we are calling
13140 // from the top, we may have already computed our adjustment with
13141 // an earlier hidden adjustment that isn't really for us... if
13142 // so, use the new hidden adjustment.
13143 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013144 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013145 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013146 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013147 }
13148
13149 if (app.thread == null) {
13150 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013151 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013152 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 }
13154
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013155 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13156 app.adjSource = null;
13157 app.adjTarget = null;
13158 app.empty = false;
13159 app.hidden = false;
13160
13161 final int activitiesSize = app.activities.size();
13162
Dianne Hackborn7d608422011-08-07 16:24:18 -070013163 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013164 // The max adjustment doesn't allow this app to be anything
13165 // below foreground, so it is not worth doing work for it.
13166 app.adjType = "fixed";
13167 app.adjSeq = mAdjSeq;
13168 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013169 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013170 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013171 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013172 // System process can do UI, and when they do we want to have
13173 // them trim their memory after the user leaves the UI. To
13174 // facilitate this, here we need to determine whether or not it
13175 // is currently showing UI.
13176 app.systemNoUi = true;
13177 if (app == TOP_APP) {
13178 app.systemNoUi = false;
13179 } else if (activitiesSize > 0) {
13180 for (int j = 0; j < activitiesSize; j++) {
13181 final ActivityRecord r = app.activities.get(j);
13182 if (r.visible) {
13183 app.systemNoUi = false;
13184 break;
13185 }
13186 }
13187 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013188 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013189 }
13190
13191 final boolean hadForegroundActivities = app.foregroundActivities;
13192
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013193 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013194 app.keeping = false;
13195 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196
The Android Open Source Project4df24232009-03-05 14:34:35 -080013197 // Determine the importance of the process, starting with most
13198 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013199 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013200 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013201 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013202 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013203 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013204 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013205 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013206 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013207 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013208 } else if (app.instrumentationClass != null) {
13209 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013210 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013211 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013212 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013213 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013214 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013215 // counts as being in the foreground for OOM killer purposes.
13216 // It's placed in a sched group based on the nature of the
13217 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013218 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013219 schedGroup = (queue == mFgBroadcastQueue)
13220 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013221 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013222 } else if (app.executingServices.size() > 0) {
13223 // An app that is currently executing a service callback also
13224 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013225 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013226 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013227 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013228 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013229 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013230 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013231 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013232 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013233 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013234 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013235 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013236 // A very not-needed process. If this is lower in the lru list,
13237 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013238 adj = hiddenAdj;
13239 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013240 app.hidden = true;
13241 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013242 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013243 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013244
13245 // Examine all activities if not already foreground.
13246 if (!app.foregroundActivities && activitiesSize > 0) {
13247 for (int j = 0; j < activitiesSize; j++) {
13248 final ActivityRecord r = app.activities.get(j);
13249 if (r.visible) {
13250 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013251 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13252 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013253 app.adjType = "visible";
13254 }
13255 schedGroup = Process.THREAD_GROUP_DEFAULT;
13256 app.hidden = false;
13257 app.foregroundActivities = true;
13258 break;
13259 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13260 || r.state == ActivityState.STOPPING) {
13261 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013262 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13263 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013264 app.adjType = "stopping";
13265 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013266 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013267 app.foregroundActivities = true;
13268 }
13269 }
13270 }
13271
Dianne Hackborn7d608422011-08-07 16:24:18 -070013272 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013273 if (app.foregroundServices) {
13274 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013275 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013276 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013277 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013278 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013279 } else if (app.forcingToForeground != null) {
13280 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013281 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013282 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013283 app.adjType = "force-foreground";
13284 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013285 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013286 }
13287 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013288
Dianne Hackborn7d608422011-08-07 16:24:18 -070013289 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013290 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013291 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013292 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013293 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013294 app.adjType = "heavy";
13295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013296
Dianne Hackborn7d608422011-08-07 16:24:18 -070013297 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013298 // This process is hosting what we currently consider to be the
13299 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013300 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013301 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013302 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013303 app.adjType = "home";
13304 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013305
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013306 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13307 && app.activities.size() > 0) {
13308 // This was the previous process that showed UI to the user.
13309 // We want to try to keep it around more aggressively, to give
13310 // a good experience around switching between two apps.
13311 adj = ProcessList.PREVIOUS_APP_ADJ;
13312 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13313 app.hidden = false;
13314 app.adjType = "previous";
13315 }
13316
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013317 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13318 + " reason=" + app.adjType);
13319
The Android Open Source Project4df24232009-03-05 14:34:35 -080013320 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013321 // there are applications dependent on our services or providers, but
13322 // this gives us a baseline and makes sure we don't get into an
13323 // infinite recursion.
13324 app.adjSeq = mAdjSeq;
13325 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013326
Christopher Tate6fa95972009-06-05 18:43:55 -070013327 if (mBackupTarget != null && app == mBackupTarget.app) {
13328 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013329 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013330 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013331 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013332 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013333 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013334 }
13335 }
13336
Dianne Hackborn7d608422011-08-07 16:24:18 -070013337 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013338 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013339 final long now = SystemClock.uptimeMillis();
13340 // This process is more important if the top activity is
13341 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013342 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013343 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013344 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013345 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013346 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013347 // If this process has shown some UI, let it immediately
13348 // go to the LRU list because it may be pretty heavy with
13349 // UI stuff. We'll tag it with a label just to help
13350 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013351 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013352 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013354 } else {
13355 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13356 // This service has seen some activity within
13357 // recent memory, so we will keep its process ahead
13358 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013359 if (adj > ProcessList.SERVICE_ADJ) {
13360 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013361 app.adjType = "started-services";
13362 app.hidden = false;
13363 }
13364 }
13365 // If we have let the service slide into the background
13366 // state, still have some text describing what it is doing
13367 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013368 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013369 app.adjType = "started-bg-services";
13370 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013371 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013372 // Don't kill this process because it is doing work; it
13373 // has said it is doing work.
13374 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013375 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013376 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013377 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013378 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013379 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013380 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013381 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013382 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013383 // XXX should compute this based on the max of
13384 // all connected clients.
13385 ConnectionRecord cr = clist.get(i);
13386 if (cr.binding.client == app) {
13387 // Binding to ourself is not interesting.
13388 continue;
13389 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013390 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013391 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013392 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013393 int myHiddenAdj = hiddenAdj;
13394 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013395 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013396 myHiddenAdj = client.hiddenAdj;
13397 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013398 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013399 }
13400 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013401 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013402 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013403 String adjType = null;
13404 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13405 // Not doing bind OOM management, so treat
13406 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013407 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013408 // If this process has shown some UI, let it immediately
13409 // go to the LRU list because it may be pretty heavy with
13410 // UI stuff. We'll tag it with a label just to help
13411 // debug and understand what is going on.
13412 if (adj > clientAdj) {
13413 adjType = "bound-bg-ui-services";
13414 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013415 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013416 clientAdj = adj;
13417 } else {
13418 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13419 // This service has not seen activity within
13420 // recent memory, so allow it to drop to the
13421 // LRU list if there is no other reason to keep
13422 // it around. We'll also tag it with a label just
13423 // to help debug and undertand what is going on.
13424 if (adj > clientAdj) {
13425 adjType = "bound-bg-services";
13426 }
13427 clientAdj = adj;
13428 }
13429 }
13430 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013431 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013432 // If this process has recently shown UI, and
13433 // the process that is binding to it is less
13434 // important than being visible, then we don't
13435 // care about the binding as much as we care
13436 // about letting this process get into the LRU
13437 // list to be killed and restarted if needed for
13438 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013439 if (app.hasShownUi && app != mHomeProcess
13440 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013441 adjType = "bound-bg-ui-services";
13442 } else {
13443 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13444 |Context.BIND_IMPORTANT)) != 0) {
13445 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013446 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13447 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13448 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13449 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13450 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013451 adj = clientAdj;
13452 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013453 app.pendingUiClean = true;
13454 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13455 adj = ProcessList.VISIBLE_APP_ADJ;
13456 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013457 }
13458 if (!client.hidden) {
13459 app.hidden = false;
13460 }
13461 if (client.keeping) {
13462 app.keeping = true;
13463 }
13464 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013465 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013466 }
13467 if (adjType != null) {
13468 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013469 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13470 .REASON_SERVICE_IN_USE;
13471 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013472 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013473 app.adjTarget = s.name;
13474 }
13475 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13476 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13477 schedGroup = Process.THREAD_GROUP_DEFAULT;
13478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479 }
13480 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013481 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13482 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013483 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013484 (a.visible || a.state == ActivityState.RESUMED
13485 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013486 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013487 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13488 schedGroup = Process.THREAD_GROUP_DEFAULT;
13489 }
13490 app.hidden = false;
13491 app.adjType = "service";
13492 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13493 .REASON_SERVICE_IN_USE;
13494 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013495 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013496 app.adjTarget = s.name;
13497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 }
13500 }
13501 }
13502 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013503
Dianne Hackborn287952c2010-09-22 22:34:31 -070013504 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013505 // would like to avoid killing it unless it would prevent the current
13506 // application from running. By default we put the process in
13507 // with the rest of the background processes; as we scan through
13508 // its services we may bump it up from there.
13509 if (adj > hiddenAdj) {
13510 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013511 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013512 app.adjType = "bg-services";
13513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013514 }
13515
Dianne Hackborn7d608422011-08-07 16:24:18 -070013516 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013517 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013518 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013519 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013520 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013521 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013522 if (cpr.clients.size() != 0) {
13523 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013524 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013526 if (client == app) {
13527 // Being our own client is not interesting.
13528 continue;
13529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013530 int myHiddenAdj = hiddenAdj;
13531 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013532 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013533 myHiddenAdj = client.hiddenAdj;
13534 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013535 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013536 }
13537 }
13538 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013539 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013540 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013541 if (app.hasShownUi && app != mHomeProcess
13542 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013543 app.adjType = "bg-ui-provider";
13544 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013545 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13546 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013547 app.adjType = "provider";
13548 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013549 if (!client.hidden) {
13550 app.hidden = false;
13551 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013552 if (client.keeping) {
13553 app.keeping = true;
13554 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013555 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13556 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013557 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013558 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013559 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013560 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013561 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13562 schedGroup = Process.THREAD_GROUP_DEFAULT;
13563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013564 }
13565 }
13566 // If the provider has external (non-framework) process
13567 // dependencies, ensure that its adjustment is at least
13568 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013569 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013570 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13571 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013572 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013573 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013574 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013575 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013576 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013577 }
13578 }
13579 }
13580 }
13581
13582 app.curRawAdj = adj;
13583
Joe Onorato8a9b2202010-02-26 18:56:32 -080013584 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013585 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13586 if (adj > app.maxAdj) {
13587 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013588 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013589 schedGroup = Process.THREAD_GROUP_DEFAULT;
13590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013591 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013592 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013593 app.keeping = true;
13594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013595
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013596 if (app.hasAboveClient) {
13597 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13598 // then we need to drop its adjustment to be lower than the service's
13599 // in order to honor the request. We want to drop it by one adjustment
13600 // level... but there is special meaning applied to various levels so
13601 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013602 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013603 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013604 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13605 adj = ProcessList.VISIBLE_APP_ADJ;
13606 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13607 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13608 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13609 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013610 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013611 adj++;
13612 }
13613 }
13614
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013615 if (adj == ProcessList.SERVICE_ADJ) {
13616 if (doingAll) {
13617 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13618 mNewNumServiceProcs++;
13619 }
13620 if (app.serviceb) {
13621 adj = ProcessList.SERVICE_B_ADJ;
13622 }
13623 } else {
13624 app.serviceb = false;
13625 }
13626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013627 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013628 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013629
13630 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013631 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13632 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013633 }
13634
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013635 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 }
13637
13638 /**
13639 * Ask a given process to GC right now.
13640 */
13641 final void performAppGcLocked(ProcessRecord app) {
13642 try {
13643 app.lastRequestedGc = SystemClock.uptimeMillis();
13644 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013645 if (app.reportLowMemory) {
13646 app.reportLowMemory = false;
13647 app.thread.scheduleLowMemory();
13648 } else {
13649 app.thread.processInBackground();
13650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013651 }
13652 } catch (Exception e) {
13653 // whatever.
13654 }
13655 }
13656
13657 /**
13658 * Returns true if things are idle enough to perform GCs.
13659 */
Josh Bartel7f208742010-02-25 11:01:44 -060013660 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013661 boolean processingBroadcasts = false;
13662 for (BroadcastQueue q : mBroadcastQueues) {
13663 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13664 processingBroadcasts = true;
13665 }
13666 }
13667 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013668 && (mSleeping || (mMainStack.mResumedActivity != null &&
13669 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013670 }
13671
13672 /**
13673 * Perform GCs on all processes that are waiting for it, but only
13674 * if things are idle.
13675 */
13676 final void performAppGcsLocked() {
13677 final int N = mProcessesToGc.size();
13678 if (N <= 0) {
13679 return;
13680 }
Josh Bartel7f208742010-02-25 11:01:44 -060013681 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 while (mProcessesToGc.size() > 0) {
13683 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013684 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013685 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13686 <= SystemClock.uptimeMillis()) {
13687 // To avoid spamming the system, we will GC processes one
13688 // at a time, waiting a few seconds between each.
13689 performAppGcLocked(proc);
13690 scheduleAppGcsLocked();
13691 return;
13692 } else {
13693 // It hasn't been long enough since we last GCed this
13694 // process... put it in the list to wait for its time.
13695 addProcessToGcListLocked(proc);
13696 break;
13697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013698 }
13699 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013700
13701 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013702 }
13703 }
13704
13705 /**
13706 * If all looks good, perform GCs on all processes waiting for them.
13707 */
13708 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013709 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013710 performAppGcsLocked();
13711 return;
13712 }
13713 // Still not idle, wait some more.
13714 scheduleAppGcsLocked();
13715 }
13716
13717 /**
13718 * Schedule the execution of all pending app GCs.
13719 */
13720 final void scheduleAppGcsLocked() {
13721 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013722
13723 if (mProcessesToGc.size() > 0) {
13724 // Schedule a GC for the time to the next process.
13725 ProcessRecord proc = mProcessesToGc.get(0);
13726 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13727
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013728 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013729 long now = SystemClock.uptimeMillis();
13730 if (when < (now+GC_TIMEOUT)) {
13731 when = now + GC_TIMEOUT;
13732 }
13733 mHandler.sendMessageAtTime(msg, when);
13734 }
13735 }
13736
13737 /**
13738 * Add a process to the array of processes waiting to be GCed. Keeps the
13739 * list in sorted order by the last GC time. The process can't already be
13740 * on the list.
13741 */
13742 final void addProcessToGcListLocked(ProcessRecord proc) {
13743 boolean added = false;
13744 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13745 if (mProcessesToGc.get(i).lastRequestedGc <
13746 proc.lastRequestedGc) {
13747 added = true;
13748 mProcessesToGc.add(i+1, proc);
13749 break;
13750 }
13751 }
13752 if (!added) {
13753 mProcessesToGc.add(0, proc);
13754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013755 }
13756
13757 /**
13758 * Set up to ask a process to GC itself. This will either do it
13759 * immediately, or put it on the list of processes to gc the next
13760 * time things are idle.
13761 */
13762 final void scheduleAppGcLocked(ProcessRecord app) {
13763 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013764 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013765 return;
13766 }
13767 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013768 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013769 scheduleAppGcsLocked();
13770 }
13771 }
13772
Dianne Hackborn287952c2010-09-22 22:34:31 -070013773 final void checkExcessivePowerUsageLocked(boolean doKills) {
13774 updateCpuStatsNow();
13775
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013776 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013777 boolean doWakeKills = doKills;
13778 boolean doCpuKills = doKills;
13779 if (mLastPowerCheckRealtime == 0) {
13780 doWakeKills = false;
13781 }
13782 if (mLastPowerCheckUptime == 0) {
13783 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013784 }
13785 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013786 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013787 }
13788 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013789 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13790 final long curUptime = SystemClock.uptimeMillis();
13791 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13792 mLastPowerCheckRealtime = curRealtime;
13793 mLastPowerCheckUptime = curUptime;
13794 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13795 doWakeKills = false;
13796 }
13797 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13798 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013799 }
13800 int i = mLruProcesses.size();
13801 while (i > 0) {
13802 i--;
13803 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013804 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013805 long wtime;
13806 synchronized (stats) {
13807 wtime = stats.getProcessWakeTime(app.info.uid,
13808 app.pid, curRealtime);
13809 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013810 long wtimeUsed = wtime - app.lastWakeTime;
13811 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13812 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013813 StringBuilder sb = new StringBuilder(128);
13814 sb.append("Wake for ");
13815 app.toShortString(sb);
13816 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013817 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013818 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013819 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013820 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013821 sb.append((wtimeUsed*100)/realtimeSince);
13822 sb.append("%)");
13823 Slog.i(TAG, sb.toString());
13824 sb.setLength(0);
13825 sb.append("CPU for ");
13826 app.toShortString(sb);
13827 sb.append(": over ");
13828 TimeUtils.formatDuration(uptimeSince, sb);
13829 sb.append(" used ");
13830 TimeUtils.formatDuration(cputimeUsed, sb);
13831 sb.append(" (");
13832 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013833 sb.append("%)");
13834 Slog.i(TAG, sb.toString());
13835 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013836 // If a process has held a wake lock for more
13837 // than 50% of the time during this period,
13838 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013839 if (doWakeKills && realtimeSince > 0
13840 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13841 synchronized (stats) {
13842 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13843 realtimeSince, wtimeUsed);
13844 }
13845 Slog.w(TAG, "Excessive wake lock in " + app.processName
13846 + " (pid " + app.pid + "): held " + wtimeUsed
13847 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013848 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13849 app.processName, app.setAdj, "excessive wake lock");
13850 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013851 } else if (doCpuKills && uptimeSince > 0
13852 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13853 synchronized (stats) {
13854 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13855 uptimeSince, cputimeUsed);
13856 }
13857 Slog.w(TAG, "Excessive CPU in " + app.processName
13858 + " (pid " + app.pid + "): used " + cputimeUsed
13859 + " during " + uptimeSince);
13860 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13861 app.processName, app.setAdj, "excessive cpu");
13862 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013863 } else {
13864 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013865 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013866 }
13867 }
13868 }
13869 }
13870
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013871 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013872 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013873 app.hiddenAdj = hiddenAdj;
13874
13875 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013876 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013877 }
13878
Dianne Hackborn287952c2010-09-22 22:34:31 -070013879 final boolean wasKeeping = app.keeping;
13880
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013881 boolean success = true;
13882
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013883 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013884
Jeff Brown10e89712011-07-08 18:52:57 -070013885 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013886 if (false) {
13887 // Removing for now. Forcing GCs is not so useful anymore
13888 // with Dalvik, and the new memory level hint facility is
13889 // better for what we need to do these days.
13890 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13891 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13892 // If this app is transitioning from foreground to
13893 // non-foreground, have it do a gc.
13894 scheduleAppGcLocked(app);
13895 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13896 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13897 // Likewise do a gc when an app is moving in to the
13898 // background (such as a service stopping).
13899 scheduleAppGcLocked(app);
13900 }
Jeff Brown10e89712011-07-08 18:52:57 -070013901 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013902
Jeff Brown10e89712011-07-08 18:52:57 -070013903 if (wasKeeping && !app.keeping) {
13904 // This app is no longer something we want to keep. Note
13905 // its current wake lock time to later know to kill it if
13906 // it is not behaving well.
13907 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13908 synchronized (stats) {
13909 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13910 app.pid, SystemClock.elapsedRealtime());
13911 }
13912 app.lastCpuTime = app.curCpuTime;
13913 }
13914
13915 app.setRawAdj = app.curRawAdj;
13916 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013917
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013918 if (app.curAdj != app.setAdj) {
13919 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013920 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013921 TAG, "Set " + app.pid + " " + app.processName +
13922 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013923 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013924 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013925 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013926 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013927 }
13928 }
13929 if (app.setSchedGroup != app.curSchedGroup) {
13930 app.setSchedGroup = app.curSchedGroup;
13931 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13932 "Setting process group of " + app.processName
13933 + " to " + app.curSchedGroup);
13934 if (app.waitingToKill != null &&
13935 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13936 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13937 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13938 app.processName, app.setAdj, app.waitingToKill);
13939 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013940 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013941 } else {
13942 if (true) {
13943 long oldId = Binder.clearCallingIdentity();
13944 try {
13945 Process.setProcessGroup(app.pid, app.curSchedGroup);
13946 } catch (Exception e) {
13947 Slog.w(TAG, "Failed setting process group of " + app.pid
13948 + " to " + app.curSchedGroup);
13949 e.printStackTrace();
13950 } finally {
13951 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013952 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013953 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013954 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013955 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013956 app.thread.setSchedulingGroup(app.curSchedGroup);
13957 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013958 }
13959 }
13960 }
13961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013962 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013963 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013964 }
13965
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013966 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013967 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013968 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013969 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013970 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013971 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013972 }
13973 }
13974 return resumedActivity;
13975 }
13976
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013977 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013978 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013979 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13980 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013981 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13982 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013983
13984 mAdjSeq++;
13985
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013986 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013987 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13988 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013989 if (nowHidden != wasHidden) {
13990 // Changed to/from hidden state, so apps after it in the LRU
13991 // list may also be changed.
13992 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013993 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013994 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013995 }
13996
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013997 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013998 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013999 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14000
14001 if (false) {
14002 RuntimeException e = new RuntimeException();
14003 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014004 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014005 }
14006
14007 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014008 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014009
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014010 // Let's determine how many processes we have running vs.
14011 // how many slots we have for background processes; we may want
14012 // to put multiple processes in a slot of there are enough of
14013 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014014 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014015 int factor = (mLruProcesses.size()-4)/numSlots;
14016 if (factor < 1) factor = 1;
14017 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014018 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014019
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014020 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014021 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014022 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014023 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014024 while (i > 0) {
14025 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014026 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014027 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014028 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14029 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014030 && app.curAdj == curHiddenAdj) {
14031 step++;
14032 if (step >= factor) {
14033 step = 0;
14034 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014035 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014036 }
14037 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014038 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014039 numHidden++;
14040 if (numHidden > mProcessLimit) {
14041 Slog.i(TAG, "No longer want " + app.processName
14042 + " (pid " + app.pid + "): hidden #" + numHidden);
14043 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14044 app.processName, app.setAdj, "too many background");
14045 app.killedBackground = true;
14046 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014047 }
14048 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014049 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14050 // If this is an isolated process, and there are no
14051 // services running in it, then the process is no longer
14052 // needed. We agressively kill these because we can by
14053 // definition not re-use the same process again, and it is
14054 // good to avoid having whatever code was running in them
14055 // left sitting around after no longer needed.
14056 Slog.i(TAG, "Isolated process " + app.processName
14057 + " (pid " + app.pid + ") no longer needed");
14058 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14059 app.processName, app.setAdj, "isolated not needed");
14060 app.killedBackground = true;
14061 Process.killProcessQuiet(app.pid);
14062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014063 }
14064 }
14065
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014066 mNumServiceProcs = mNewNumServiceProcs;
14067
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014068 // Now determine the memory trimming level of background processes.
14069 // Unfortunately we need to start at the back of the list to do this
14070 // properly. We only do this if the number of background apps we
14071 // are managing to keep around is less than half the maximum we desire;
14072 // if we are keeping a good number around, we'll let them use whatever
14073 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014074 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014075 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014076 factor = numHidden/3;
14077 int minFactor = 2;
14078 if (mHomeProcess != null) minFactor++;
14079 if (mPreviousProcess != null) minFactor++;
14080 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014081 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014082 int fgTrimLevel;
14083 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14084 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14085 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14086 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14087 } else {
14088 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14089 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014090 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014091 for (i=0; i<N; i++) {
14092 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014093 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14094 && app.curAdj != ProcessList.SERVICE_B_ADJ
14095 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014096 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14097 try {
14098 app.thread.scheduleTrimMemory(curLevel);
14099 } catch (RemoteException e) {
14100 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014101 if (false) {
14102 // For now we won't do this; our memory trimming seems
14103 // to be good enough at this point that destroying
14104 // activities causes more harm than good.
14105 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14106 && app != mHomeProcess && app != mPreviousProcess) {
14107 // For these apps we will also finish their activities
14108 // to help them free memory.
14109 mMainStack.destroyActivitiesLocked(app, false, "trim");
14110 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014111 }
14112 }
14113 app.trimMemoryLevel = curLevel;
14114 step++;
14115 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014116 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014117 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014118 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14119 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014120 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014121 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14122 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014123 break;
14124 }
14125 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014126 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014127 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014128 && app.thread != null) {
14129 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014130 app.thread.scheduleTrimMemory(
14131 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014132 } catch (RemoteException e) {
14133 }
14134 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014135 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014136 } else {
14137 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14138 && app.pendingUiClean) {
14139 // If this application is now in the background and it
14140 // had done UI, then give it the special trim level to
14141 // have it free UI resources.
14142 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14143 if (app.trimMemoryLevel < level && app.thread != null) {
14144 try {
14145 app.thread.scheduleTrimMemory(level);
14146 } catch (RemoteException e) {
14147 }
14148 }
14149 app.pendingUiClean = false;
14150 }
14151 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014152 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014153 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014154 } catch (RemoteException e) {
14155 }
14156 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014157 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014158 }
14159 }
14160 } else {
14161 final int N = mLruProcesses.size();
14162 for (i=0; i<N; i++) {
14163 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014164 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014165 && app.pendingUiClean) {
14166 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14167 && app.thread != null) {
14168 try {
14169 app.thread.scheduleTrimMemory(
14170 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14171 } catch (RemoteException e) {
14172 }
14173 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014174 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014175 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014176 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014177 }
14178 }
14179
14180 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014181 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014183 }
14184
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014185 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014186 synchronized (this) {
14187 int i;
14188
14189 // First remove any unused application processes whose package
14190 // has been removed.
14191 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14192 final ProcessRecord app = mRemovedProcesses.get(i);
14193 if (app.activities.size() == 0
14194 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014195 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014196 TAG, "Exiting empty application process "
14197 + app.processName + " ("
14198 + (app.thread != null ? app.thread.asBinder() : null)
14199 + ")\n");
14200 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014201 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14202 app.processName, app.setAdj, "empty");
14203 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014204 } else {
14205 try {
14206 app.thread.scheduleExit();
14207 } catch (Exception e) {
14208 // Ignore exceptions.
14209 }
14210 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014211 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014212 mRemovedProcesses.remove(i);
14213
14214 if (app.persistent) {
14215 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014216 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014217 }
14218 }
14219 }
14220 }
14221
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014222 // Now update the oom adj for all processes.
14223 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014224 }
14225 }
14226
14227 /** This method sends the specified signal to each of the persistent apps */
14228 public void signalPersistentProcesses(int sig) throws RemoteException {
14229 if (sig != Process.SIGNAL_USR1) {
14230 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14231 }
14232
14233 synchronized (this) {
14234 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14235 != PackageManager.PERMISSION_GRANTED) {
14236 throw new SecurityException("Requires permission "
14237 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14238 }
14239
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014240 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14241 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014242 if (r.thread != null && r.persistent) {
14243 Process.sendSignal(r.pid, sig);
14244 }
14245 }
14246 }
14247 }
14248
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014249 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14250 if (proc == null || proc == mProfileProc) {
14251 proc = mProfileProc;
14252 path = mProfileFile;
14253 profileType = mProfileType;
14254 clearProfilerLocked();
14255 }
14256 if (proc == null) {
14257 return;
14258 }
14259 try {
14260 proc.thread.profilerControl(false, path, null, profileType);
14261 } catch (RemoteException e) {
14262 throw new IllegalStateException("Process disappeared");
14263 }
14264 }
14265
14266 private void clearProfilerLocked() {
14267 if (mProfileFd != null) {
14268 try {
14269 mProfileFd.close();
14270 } catch (IOException e) {
14271 }
14272 }
14273 mProfileApp = null;
14274 mProfileProc = null;
14275 mProfileFile = null;
14276 mProfileType = 0;
14277 mAutoStopProfiler = false;
14278 }
14279
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014280 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014281 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014282
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014283 try {
14284 synchronized (this) {
14285 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14286 // its own permission.
14287 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14288 != PackageManager.PERMISSION_GRANTED) {
14289 throw new SecurityException("Requires permission "
14290 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014291 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014292
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014293 if (start && fd == null) {
14294 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014295 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014296
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014297 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014298 if (process != null) {
14299 try {
14300 int pid = Integer.parseInt(process);
14301 synchronized (mPidsSelfLocked) {
14302 proc = mPidsSelfLocked.get(pid);
14303 }
14304 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014305 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014306
14307 if (proc == null) {
14308 HashMap<String, SparseArray<ProcessRecord>> all
14309 = mProcessNames.getMap();
14310 SparseArray<ProcessRecord> procs = all.get(process);
14311 if (procs != null && procs.size() > 0) {
14312 proc = procs.valueAt(0);
14313 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014314 }
14315 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014316
14317 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014318 throw new IllegalArgumentException("Unknown process: " + process);
14319 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014320
14321 if (start) {
14322 stopProfilerLocked(null, null, 0);
14323 setProfileApp(proc.info, proc.processName, path, fd, false);
14324 mProfileProc = proc;
14325 mProfileType = profileType;
14326 try {
14327 fd = fd.dup();
14328 } catch (IOException e) {
14329 fd = null;
14330 }
14331 proc.thread.profilerControl(start, path, fd, profileType);
14332 fd = null;
14333 mProfileFd = null;
14334 } else {
14335 stopProfilerLocked(proc, path, profileType);
14336 if (fd != null) {
14337 try {
14338 fd.close();
14339 } catch (IOException e) {
14340 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014341 }
14342 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014343
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014344 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014345 }
14346 } catch (RemoteException e) {
14347 throw new IllegalStateException("Process disappeared");
14348 } finally {
14349 if (fd != null) {
14350 try {
14351 fd.close();
14352 } catch (IOException e) {
14353 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014354 }
14355 }
14356 }
Andy McFadden824c5102010-07-09 16:26:57 -070014357
14358 public boolean dumpHeap(String process, boolean managed,
14359 String path, ParcelFileDescriptor fd) throws RemoteException {
14360
14361 try {
14362 synchronized (this) {
14363 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14364 // its own permission (same as profileControl).
14365 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14366 != PackageManager.PERMISSION_GRANTED) {
14367 throw new SecurityException("Requires permission "
14368 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14369 }
14370
14371 if (fd == null) {
14372 throw new IllegalArgumentException("null fd");
14373 }
14374
14375 ProcessRecord proc = null;
14376 try {
14377 int pid = Integer.parseInt(process);
14378 synchronized (mPidsSelfLocked) {
14379 proc = mPidsSelfLocked.get(pid);
14380 }
14381 } catch (NumberFormatException e) {
14382 }
14383
14384 if (proc == null) {
14385 HashMap<String, SparseArray<ProcessRecord>> all
14386 = mProcessNames.getMap();
14387 SparseArray<ProcessRecord> procs = all.get(process);
14388 if (procs != null && procs.size() > 0) {
14389 proc = procs.valueAt(0);
14390 }
14391 }
14392
14393 if (proc == null || proc.thread == null) {
14394 throw new IllegalArgumentException("Unknown process: " + process);
14395 }
14396
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014397 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14398 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014399 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14400 throw new SecurityException("Process not debuggable: " + proc);
14401 }
14402 }
14403
14404 proc.thread.dumpHeap(managed, path, fd);
14405 fd = null;
14406 return true;
14407 }
14408 } catch (RemoteException e) {
14409 throw new IllegalStateException("Process disappeared");
14410 } finally {
14411 if (fd != null) {
14412 try {
14413 fd.close();
14414 } catch (IOException e) {
14415 }
14416 }
14417 }
14418 }
14419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014420 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14421 public void monitor() {
14422 synchronized (this) { }
14423 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014424
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014425 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014426 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14427 ProcessRecord processRecord = mLruProcesses.get(i);
14428 try {
14429 if (processRecord.thread != null) {
14430 processRecord.thread.setCoreSettings(settings);
14431 }
14432 } catch (RemoteException re) {
14433 /* ignore */
14434 }
14435 }
14436 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014437
14438 // Multi-user methods
14439
Amith Yamasani742a6712011-05-04 14:49:28 -070014440 private int mCurrentUserId;
14441 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014442 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14443
14444 public interface UserListener {
14445 public void onUserChanged(int userId);
14446
14447 public void onUserAdded(int userId);
14448
14449 public void onUserRemoved(int userId);
14450
14451 public void onUserLoggedOut(int userId);
14452 }
14453
14454 public void addUserListener(UserListener listener) {
14455 synchronized (this) {
14456 if (!mUserListeners.contains(listener)) {
14457 mUserListeners.add(listener);
14458 }
14459 }
14460 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014461
14462 public boolean switchUser(int userId) {
14463 final int callingUid = Binder.getCallingUid();
14464 if (callingUid != 0 && callingUid != Process.myUid()) {
14465 Slog.e(TAG, "Trying to switch user from unauthorized app");
14466 return false;
14467 }
14468 if (mCurrentUserId == userId)
14469 return true;
14470
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014471 ArrayList<UserListener> listeners;
14472
Amith Yamasani742a6712011-05-04 14:49:28 -070014473 synchronized (this) {
14474 // Check if user is already logged in, otherwise check if user exists first before
14475 // adding to the list of logged in users.
14476 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14477 if (!userExists(userId)) {
14478 return false;
14479 }
14480 mLoggedInUsers.append(userId, userId);
14481 }
14482
14483 mCurrentUserId = userId;
14484 boolean haveActivities = mMainStack.switchUser(userId);
14485 if (!haveActivities) {
14486 startHomeActivityLocked(userId);
14487 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014488
14489 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14490 }
14491 // Inform the listeners
14492 for (UserListener listener : listeners) {
14493 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014494 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014495 return true;
14496 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014497
14498 private boolean userExists(int userId) {
14499 try {
14500 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14501 for (UserInfo user : users) {
14502 if (user.id == userId) {
14503 return true;
14504 }
14505 }
14506 } catch (RemoteException re) {
14507 // Won't happen, in same process
14508 }
14509
14510 return false;
14511 }
14512
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014513 private void checkValidCaller(int uid, int userId) {
14514 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14515
14516 throw new SecurityException("Caller uid=" + uid
14517 + " is not privileged to communicate with user=" + userId);
14518 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014519
14520 private int applyUserId(int uid, int userId) {
14521 return UserId.getUid(userId, uid);
14522 }
14523
14524 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014525 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014526 ApplicationInfo newInfo = new ApplicationInfo(info);
14527 newInfo.uid = applyUserId(info.uid, userId);
14528 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14529 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14530 + info.packageName;
14531 }
14532 return newInfo;
14533 }
14534
14535 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014536 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014537 || userId < 1) {
14538 return aInfo;
14539 }
14540
14541 ActivityInfo info = new ActivityInfo(aInfo);
14542 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14543 return info;
14544 }
14545
14546 static class ServiceMap {
14547
14548 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14549 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14550 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14551 mServicesByIntentPerUser = new SparseArray<
14552 HashMap<Intent.FilterComparison, ServiceRecord>>();
14553
14554 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14555 // TODO: Deal with global services
14556 if (DEBUG_MU)
14557 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14558 return getServices(callingUser).get(name);
14559 }
14560
14561 ServiceRecord getServiceByName(ComponentName name) {
14562 return getServiceByName(name, -1);
14563 }
14564
14565 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14566 // TODO: Deal with global services
14567 if (DEBUG_MU)
14568 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14569 return getServicesByIntent(callingUser).get(filter);
14570 }
14571
14572 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14573 return getServiceByIntent(filter, -1);
14574 }
14575
14576 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14577 // TODO: Deal with global services
14578 getServices(callingUser).put(name, value);
14579 }
14580
14581 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14582 ServiceRecord value) {
14583 // TODO: Deal with global services
14584 getServicesByIntent(callingUser).put(filter, value);
14585 }
14586
14587 void removeServiceByName(ComponentName name, int callingUser) {
14588 // TODO: Deal with global services
14589 ServiceRecord removed = getServices(callingUser).remove(name);
14590 if (DEBUG_MU)
14591 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14592 + " removed=" + removed);
14593 }
14594
14595 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14596 // TODO: Deal with global services
14597 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14598 if (DEBUG_MU)
14599 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14600 + " removed=" + removed);
14601 }
14602
14603 Collection<ServiceRecord> getAllServices(int callingUser) {
14604 // TODO: Deal with global services
14605 return getServices(callingUser).values();
14606 }
14607
14608 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14609 HashMap map = mServicesByNamePerUser.get(callingUser);
14610 if (map == null) {
14611 map = new HashMap<ComponentName, ServiceRecord>();
14612 mServicesByNamePerUser.put(callingUser, map);
14613 }
14614 return map;
14615 }
14616
14617 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14618 int callingUser) {
14619 HashMap map = mServicesByIntentPerUser.get(callingUser);
14620 if (map == null) {
14621 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14622 mServicesByIntentPerUser.put(callingUser, map);
14623 }
14624 return map;
14625 }
14626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014627}