blob: ad8fea9ab67894ae6a719dc30dd3ac4edc5b0d98 [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 Hackbornc68c9132011-07-29 01:25:18 -070055import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ComponentName;
57import android.content.ContentResolver;
58import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020059import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.Intent;
61import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070062import android.content.IIntentReceiver;
63import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070064import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.pm.ActivityInfo;
66import android.content.pm.ApplicationInfo;
67import android.content.pm.ConfigurationInfo;
68import android.content.pm.IPackageDataObserver;
69import android.content.pm.IPackageManager;
70import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080071import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070073import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.content.pm.ProviderInfo;
75import android.content.pm.ResolveInfo;
76import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070077import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040079import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.res.Configuration;
81import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070082import android.net.Proxy;
83import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.net.Uri;
85import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080086import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080087import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070088import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080089import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080091import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.FileUtils;
93import android.os.Handler;
94import android.os.IBinder;
95import android.os.IPermissionController;
96import android.os.Looper;
97import android.os.Message;
98import android.os.Parcel;
99import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700101import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.RemoteException;
103import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700104import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.SystemClock;
106import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700107import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700110import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800112import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.util.PrintWriterPrinter;
114import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700115import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700116import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.view.Gravity;
118import android.view.LayoutInflater;
119import android.view.View;
120import android.view.WindowManager;
121import android.view.WindowManagerPolicy;
122
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700123import java.io.BufferedInputStream;
124import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700125import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700126import java.io.DataInputStream;
127import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import java.io.File;
129import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200133import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800134import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700136import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.lang.IllegalStateException;
138import java.lang.ref.WeakReference;
139import java.util.ArrayList;
Dianne Hackborncbb722e2012-02-07 18:33:49 -0800140import java.util.Arrays;
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
570 /**
571 * All of the currently running global content providers. Keys are a
572 * string containing the provider name and values are a
573 * ContentProviderRecord object containing the data about it. Note
574 * that a single provider may be published under multiple names, so
575 * there may be multiple entries here for a single one in mProvidersByClass.
576 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700577 final HashMap<String, ContentProviderRecord> mProvidersByName
578 = new HashMap<String, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579
580 /**
581 * All of the currently running global content providers. Keys are a
582 * string containing the provider's implementation class and values are a
583 * ContentProviderRecord object containing the data about it.
584 */
Dianne Hackborn1c9b2602011-08-19 14:08:43 -0700585 final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass
586 = new HashMap<ComponentName, ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
Amith Yamasani742a6712011-05-04 14:49:28 -0700588 final ProviderMap mProviderMap = new ProviderMap();
589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 /**
591 * List of content providers who have clients waiting for them. The
592 * application is currently being launched and the provider will be
593 * removed from this list once it is published.
594 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700595 final ArrayList<ContentProviderRecord> mLaunchingProviders
596 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597
598 /**
599 * Global set of specific Uri permissions that have been granted.
600 */
601 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
602 = new SparseArray<HashMap<Uri, UriPermission>>();
603
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800604 CoreSettingsObserver mCoreSettingsObserver;
605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 /**
607 * Thread-local storage used to carry caller permissions over through
608 * indirect content-provider access.
609 * @see #ActivityManagerService.openContentUri()
610 */
611 private class Identity {
612 public int pid;
613 public int uid;
614
615 Identity(int _pid, int _uid) {
616 pid = _pid;
617 uid = _uid;
618 }
619 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
622
623 /**
624 * All information we have collected about the runtime performance of
625 * any user id that can impact battery performance.
626 */
627 final BatteryStatsService mBatteryStatsService;
628
629 /**
630 * information about component usage
631 */
632 final UsageStatsService mUsageStatsService;
633
634 /**
635 * Current configuration information. HistoryRecord objects are given
636 * a reference to this object to indicate which configuration they are
637 * currently running in, so this object must be kept immutable.
638 */
639 Configuration mConfiguration = new Configuration();
640
641 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800642 * Current sequencing integer of the configuration, for skipping old
643 * configurations.
644 */
645 int mConfigurationSeq = 0;
646
647 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700648 * Hardware-reported OpenGLES version.
649 */
650 final int GL_ES_VERSION;
651
652 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 * List of initialization arguments to pass to all processes when binding applications to them.
654 * For example, references to the commonly used services.
655 */
656 HashMap<String, IBinder> mAppBindArgs;
657
658 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700659 * Temporary to avoid allocations. Protected by main lock.
660 */
661 final StringBuilder mStringBuilder = new StringBuilder(256);
662
663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 * Used to control how we initialize the service.
665 */
666 boolean mStartRunning = false;
667 ComponentName mTopComponent;
668 String mTopAction;
669 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700670 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 boolean mSystemReady = false;
672 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700673 boolean mWaitingUpdate = false;
674 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700675 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700676 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677
678 Context mContext;
679
680 int mFactoryTest;
681
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700682 boolean mCheckedForSetup;
683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700685 * The time at which we will allow normal application switches again,
686 * after a call to {@link #stopAppSwitches()}.
687 */
688 long mAppSwitchesAllowedTime;
689
690 /**
691 * This is set to true after the first switch after mAppSwitchesAllowedTime
692 * is set; any switches after that will clear the time.
693 */
694 boolean mDidAppSwitch;
695
696 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700697 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700698 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700699 long mLastPowerCheckRealtime;
700
701 /**
702 * Last time (in uptime) at which we checked for power usage.
703 */
704 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700705
706 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 * Set while we are wanting to sleep, to prevent any
708 * activities from being started/resumed.
709 */
710 boolean mSleeping = false;
711
712 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700713 * Set if we are shutting down the system, similar to sleeping.
714 */
715 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716
717 /**
718 * Task identifier that activities are currently being started
719 * in. Incremented each time a new task is created.
720 * todo: Replace this with a TokenSpace class that generates non-repeating
721 * integers that won't wrap.
722 */
723 int mCurTask = 1;
724
725 /**
726 * Current sequence id for oom_adj computation traversal.
727 */
728 int mAdjSeq = 0;
729
730 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700731 * Current sequence id for process LRU updating.
732 */
733 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734
735 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700736 * Keep track of the number of service processes we last found, to
737 * determine on the next iteration which should be B services.
738 */
739 int mNumServiceProcs = 0;
740 int mNewNumServiceProcs = 0;
741
742 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 * System monitoring: number of processes that died since the last
744 * N procs were started.
745 */
746 int[] mProcDeaths = new int[20];
747
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700748 /**
749 * This is set if we had to do a delayed dexopt of an app before launching
750 * it, to increasing the ANR timeouts in that case.
751 */
752 boolean mDidDexOpt;
753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 String mDebugApp = null;
755 boolean mWaitForDebugger = false;
756 boolean mDebugTransient = false;
757 String mOrigDebugApp = null;
758 boolean mOrigWaitForDebugger = false;
759 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700760 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700761 String mProfileApp = null;
762 ProcessRecord mProfileProc = null;
763 String mProfileFile;
764 ParcelFileDescriptor mProfileFd;
765 int mProfileType = 0;
766 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
Jeff Sharkeya4620792011-05-20 15:29:23 -0700768 final RemoteCallbackList<IProcessObserver> mProcessObservers
769 = new RemoteCallbackList<IProcessObserver>();
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 /**
772 * Callback of last caller to {@link #requestPss}.
773 */
774 Runnable mRequestPssCallback;
775
776 /**
777 * Remaining processes for which we are waiting results from the last
778 * call to {@link #requestPss}.
779 */
780 final ArrayList<ProcessRecord> mRequestPssList
781 = new ArrayList<ProcessRecord>();
782
783 /**
784 * Runtime statistics collection thread. This object's lock is used to
785 * protect all related state.
786 */
787 final Thread mProcessStatsThread;
788
789 /**
790 * Used to collect process stats when showing not responding dialog.
791 * Protected by mProcessStatsThread.
792 */
793 final ProcessStats mProcessStats = new ProcessStats(
794 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700795 final AtomicLong mLastCpuTime = new AtomicLong(0);
796 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 long mLastWriteTime = 0;
799
800 /**
801 * Set to true after the system has finished booting.
802 */
803 boolean mBooted = false;
804
Dianne Hackborn7d608422011-08-07 16:24:18 -0700805 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700806 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807
808 WindowManagerService mWindowManager;
809
810 static ActivityManagerService mSelf;
811 static ActivityThread mSystemThread;
812
813 private final class AppDeathRecipient implements IBinder.DeathRecipient {
814 final ProcessRecord mApp;
815 final int mPid;
816 final IApplicationThread mAppThread;
817
818 AppDeathRecipient(ProcessRecord app, int pid,
819 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800820 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 TAG, "New death recipient " + this
822 + " for thread " + thread.asBinder());
823 mApp = app;
824 mPid = pid;
825 mAppThread = thread;
826 }
827
828 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800829 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 TAG, "Death received in " + this
831 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 synchronized(ActivityManagerService.this) {
833 appDiedLocked(mApp, mPid, mAppThread);
834 }
835 }
836 }
837
838 static final int SHOW_ERROR_MSG = 1;
839 static final int SHOW_NOT_RESPONDING_MSG = 2;
840 static final int SHOW_FACTORY_ERROR_MSG = 3;
841 static final int UPDATE_CONFIGURATION_MSG = 4;
842 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
843 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 static final int SERVICE_TIMEOUT_MSG = 12;
845 static final int UPDATE_TIME_ZONE = 13;
846 static final int SHOW_UID_ERROR_MSG = 14;
847 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700849 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700850 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800851 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700852 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
853 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700854 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700855 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700856 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700857 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700858 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700859 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
860 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700861 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800863 static final int FIRST_ACTIVITY_STACK_MSG = 100;
864 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
865 static final int FIRST_COMPAT_MODE_MSG = 300;
866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700868 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700869 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870
871 final Handler mHandler = new Handler() {
872 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800873 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 //}
875
876 public void handleMessage(Message msg) {
877 switch (msg.what) {
878 case SHOW_ERROR_MSG: {
879 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 synchronized (ActivityManagerService.this) {
881 ProcessRecord proc = (ProcessRecord)data.get("app");
882 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800883 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 return;
885 }
886 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700887 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800888 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 d.show();
890 proc.crashDialog = d;
891 } else {
892 // The device is asleep, so just pretend that the user
893 // saw a crash dialog and hit "force quit".
894 res.set(0);
895 }
896 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700897
898 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 } break;
900 case SHOW_NOT_RESPONDING_MSG: {
901 synchronized (ActivityManagerService.this) {
902 HashMap data = (HashMap) msg.obj;
903 ProcessRecord proc = (ProcessRecord)data.get("app");
904 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800905 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 return;
907 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800908
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700909 Intent intent = new Intent("android.intent.action.ANR");
910 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800911 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
912 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700913 }
914 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800915 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700916 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700919 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 d.show();
921 proc.anrDialog = d;
922 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700923
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700924 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700926 case SHOW_STRICT_MODE_VIOLATION_MSG: {
927 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
928 synchronized (ActivityManagerService.this) {
929 ProcessRecord proc = (ProcessRecord) data.get("app");
930 if (proc == null) {
931 Slog.e(TAG, "App not found when showing strict mode dialog.");
932 break;
933 }
934 if (proc.crashDialog != null) {
935 Slog.e(TAG, "App already has strict mode dialog: " + proc);
936 return;
937 }
938 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700939 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700940 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
941 d.show();
942 proc.crashDialog = d;
943 } else {
944 // The device is asleep, so just pretend that the user
945 // saw a crash dialog and hit "force quit".
946 res.set(0);
947 }
948 }
949 ensureBootCompleted();
950 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 case SHOW_FACTORY_ERROR_MSG: {
952 Dialog d = new FactoryErrorDialog(
953 mContext, msg.getData().getCharSequence("msg"));
954 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700955 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 } break;
957 case UPDATE_CONFIGURATION_MSG: {
958 final ContentResolver resolver = mContext.getContentResolver();
959 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
960 } break;
961 case GC_BACKGROUND_PROCESSES_MSG: {
962 synchronized (ActivityManagerService.this) {
963 performAppGcsIfAppropriateLocked();
964 }
965 } break;
966 case WAIT_FOR_DEBUGGER_MSG: {
967 synchronized (ActivityManagerService.this) {
968 ProcessRecord app = (ProcessRecord)msg.obj;
969 if (msg.arg1 != 0) {
970 if (!app.waitedForDebugger) {
971 Dialog d = new AppWaitingForDebuggerDialog(
972 ActivityManagerService.this,
973 mContext, app);
974 app.waitDialog = d;
975 app.waitedForDebugger = true;
976 d.show();
977 }
978 } else {
979 if (app.waitDialog != null) {
980 app.waitDialog.dismiss();
981 app.waitDialog = null;
982 }
983 }
984 }
985 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700987 if (mDidDexOpt) {
988 mDidDexOpt = false;
989 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
990 nmsg.obj = msg.obj;
991 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
992 return;
993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 serviceTimeout((ProcessRecord)msg.obj);
995 } break;
996 case UPDATE_TIME_ZONE: {
997 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800998 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
999 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 if (r.thread != null) {
1001 try {
1002 r.thread.updateTimeZone();
1003 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001004 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
1006 }
1007 }
1008 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001009 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001010 case CLEAR_DNS_CACHE: {
1011 synchronized (ActivityManagerService.this) {
1012 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1013 ProcessRecord r = mLruProcesses.get(i);
1014 if (r.thread != null) {
1015 try {
1016 r.thread.clearDnsCache();
1017 } catch (RemoteException ex) {
1018 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1019 }
1020 }
1021 }
1022 }
1023 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001024 case UPDATE_HTTP_PROXY: {
1025 ProxyProperties proxy = (ProxyProperties)msg.obj;
1026 String host = "";
1027 String port = "";
1028 String exclList = "";
1029 if (proxy != null) {
1030 host = proxy.getHost();
1031 port = Integer.toString(proxy.getPort());
1032 exclList = proxy.getExclusionList();
1033 }
1034 synchronized (ActivityManagerService.this) {
1035 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1036 ProcessRecord r = mLruProcesses.get(i);
1037 if (r.thread != null) {
1038 try {
1039 r.thread.setHttpProxy(host, port, exclList);
1040 } catch (RemoteException ex) {
1041 Slog.w(TAG, "Failed to update http proxy for: " +
1042 r.info.processName);
1043 }
1044 }
1045 }
1046 }
1047 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001049 String title = "System UIDs Inconsistent";
1050 String text = "UIDs on the system are inconsistent, you need to wipe your"
1051 + " data partition or your device will be unstable.";
1052 Log.e(TAG, title + ": " + text);
1053 if (mShowDialogs) {
1054 // XXX This is a temporary dialog, no need to localize.
1055 AlertDialog d = new BaseErrorDialog(mContext);
1056 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1057 d.setCancelable(false);
1058 d.setTitle(title);
1059 d.setMessage(text);
1060 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1061 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1062 mUidAlert = d;
1063 d.show();
1064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 } break;
1066 case IM_FEELING_LUCKY_MSG: {
1067 if (mUidAlert != null) {
1068 mUidAlert.dismiss();
1069 mUidAlert = null;
1070 }
1071 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001073 if (mDidDexOpt) {
1074 mDidDexOpt = false;
1075 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1076 nmsg.obj = msg.obj;
1077 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1078 return;
1079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 ProcessRecord app = (ProcessRecord)msg.obj;
1081 synchronized (ActivityManagerService.this) {
1082 processStartTimedOutLocked(app);
1083 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001084 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001085 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1086 synchronized (ActivityManagerService.this) {
1087 doPendingActivityLaunchesLocked(true);
1088 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001089 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001090 case KILL_APPLICATION_MSG: {
1091 synchronized (ActivityManagerService.this) {
1092 int uid = msg.arg1;
1093 boolean restart = (msg.arg2 == 1);
1094 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001095 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001096 }
1097 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001098 case FINALIZE_PENDING_INTENT_MSG: {
1099 ((PendingIntentRecord)msg.obj).completeFinalize();
1100 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001101 case POST_HEAVY_NOTIFICATION_MSG: {
1102 INotificationManager inm = NotificationManager.getService();
1103 if (inm == null) {
1104 return;
1105 }
1106
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001107 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001108 ProcessRecord process = root.app;
1109 if (process == null) {
1110 return;
1111 }
1112
1113 try {
1114 Context context = mContext.createPackageContext(process.info.packageName, 0);
1115 String text = mContext.getString(R.string.heavy_weight_notification,
1116 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1117 Notification notification = new Notification();
1118 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1119 notification.when = 0;
1120 notification.flags = Notification.FLAG_ONGOING_EVENT;
1121 notification.tickerText = text;
1122 notification.defaults = 0; // please be quiet
1123 notification.sound = null;
1124 notification.vibrate = null;
1125 notification.setLatestEventInfo(context, text,
1126 mContext.getText(R.string.heavy_weight_notification_detail),
1127 PendingIntent.getActivity(mContext, 0, root.intent,
1128 PendingIntent.FLAG_CANCEL_CURRENT));
1129
1130 try {
1131 int[] outId = new int[1];
1132 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1133 notification, outId);
1134 } catch (RuntimeException e) {
1135 Slog.w(ActivityManagerService.TAG,
1136 "Error showing notification for heavy-weight app", e);
1137 } catch (RemoteException e) {
1138 }
1139 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001140 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001141 }
1142 } break;
1143 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1144 INotificationManager inm = NotificationManager.getService();
1145 if (inm == null) {
1146 return;
1147 }
1148 try {
1149 inm.cancelNotification("android",
1150 R.string.heavy_weight_notification);
1151 } catch (RuntimeException e) {
1152 Slog.w(ActivityManagerService.TAG,
1153 "Error canceling notification for service", e);
1154 } catch (RemoteException e) {
1155 }
1156 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001157 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1158 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001159 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001160 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001161 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1162 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001163 }
1164 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001165 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1166 synchronized (ActivityManagerService.this) {
1167 ActivityRecord ar = (ActivityRecord)msg.obj;
1168 if (mCompatModeDialog != null) {
1169 if (mCompatModeDialog.mAppInfo.packageName.equals(
1170 ar.info.applicationInfo.packageName)) {
1171 return;
1172 }
1173 mCompatModeDialog.dismiss();
1174 mCompatModeDialog = null;
1175 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001176 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001177 if (mCompatModePackages.getPackageAskCompatModeLocked(
1178 ar.packageName)) {
1179 int mode = mCompatModePackages.computeCompatModeLocked(
1180 ar.info.applicationInfo);
1181 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1182 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1183 mCompatModeDialog = new CompatModeDialog(
1184 ActivityManagerService.this, mContext,
1185 ar.info.applicationInfo);
1186 mCompatModeDialog.show();
1187 }
1188 }
1189 }
1190 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001191 break;
1192 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001193 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001194 final int pid = msg.arg1;
1195 final int uid = msg.arg2;
1196 final boolean foregroundActivities = (Boolean) msg.obj;
1197 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001198 break;
1199 }
1200 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001201 final int pid = msg.arg1;
1202 final int uid = msg.arg2;
1203 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001204 break;
1205 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001206 case REPORT_MEM_USAGE: {
1207 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1208 if (!isDebuggable) {
1209 return;
1210 }
1211 synchronized (ActivityManagerService.this) {
1212 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001213 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1214 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001215 // avoid spamming.
1216 return;
1217 }
1218 mLastMemUsageReportTime = now;
1219 }
1220 Thread thread = new Thread() {
1221 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001222 StringBuilder dropBuilder = new StringBuilder(1024);
1223 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001224 StringWriter oomSw = new StringWriter();
1225 PrintWriter oomPw = new PrintWriter(oomSw);
1226 StringWriter catSw = new StringWriter();
1227 PrintWriter catPw = new PrintWriter(catSw);
1228 String[] emptyArgs = new String[] { };
1229 StringBuilder tag = new StringBuilder(128);
1230 StringBuilder stack = new StringBuilder(128);
1231 tag.append("Low on memory -- ");
1232 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1233 tag, stack);
1234 dropBuilder.append(stack);
1235 dropBuilder.append('\n');
1236 dropBuilder.append('\n');
1237 String oomString = oomSw.toString();
1238 dropBuilder.append(oomString);
1239 dropBuilder.append('\n');
1240 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001241 try {
1242 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1243 "procrank", });
1244 final InputStreamReader converter = new InputStreamReader(
1245 proc.getInputStream());
1246 BufferedReader in = new BufferedReader(converter);
1247 String line;
1248 while (true) {
1249 line = in.readLine();
1250 if (line == null) {
1251 break;
1252 }
1253 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001254 logBuilder.append(line);
1255 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001256 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001257 dropBuilder.append(line);
1258 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001259 }
1260 converter.close();
1261 } catch (IOException e) {
1262 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001263 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001264 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001265 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001266 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001267 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001271 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001272 addErrorToDropBox("lowmem", null, "system_server", null,
1273 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001274 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001275 synchronized (ActivityManagerService.this) {
1276 long now = SystemClock.uptimeMillis();
1277 if (mLastMemUsageReportTime < now) {
1278 mLastMemUsageReportTime = now;
1279 }
1280 }
1281 }
1282 };
1283 thread.start();
1284 break;
1285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 }
1287 }
1288 };
1289
1290 public static void setSystemProcess() {
1291 try {
1292 ActivityManagerService m = mSelf;
1293
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001294 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001296 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001297 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 if (MONITOR_CPU_USAGE) {
1299 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 ServiceManager.addService("permission", new PermissionController(m));
1302
1303 ApplicationInfo info =
1304 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001305 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001306 mSystemThread.installSystemApplicationInfo(info);
1307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 synchronized (mSelf) {
1309 ProcessRecord app = mSelf.newProcessRecordLocked(
1310 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001311 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001313 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001314 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001315 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 synchronized (mSelf.mPidsSelfLocked) {
1317 mSelf.mPidsSelfLocked.put(app.pid, app);
1318 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001319 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
1321 } catch (PackageManager.NameNotFoundException e) {
1322 throw new RuntimeException(
1323 "Unable to find android system package", e);
1324 }
1325 }
1326
1327 public void setWindowManager(WindowManagerService wm) {
1328 mWindowManager = wm;
1329 }
1330
1331 public static final Context main(int factoryTest) {
1332 AThread thr = new AThread();
1333 thr.start();
1334
1335 synchronized (thr) {
1336 while (thr.mService == null) {
1337 try {
1338 thr.wait();
1339 } catch (InterruptedException e) {
1340 }
1341 }
1342 }
1343
1344 ActivityManagerService m = thr.mService;
1345 mSelf = m;
1346 ActivityThread at = ActivityThread.systemMain();
1347 mSystemThread = at;
1348 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001349 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 m.mContext = context;
1351 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001352 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353
1354 m.mBatteryStatsService.publish(context);
1355 m.mUsageStatsService.publish(context);
1356
1357 synchronized (thr) {
1358 thr.mReady = true;
1359 thr.notifyAll();
1360 }
1361
1362 m.startRunning(null, null, null, null);
1363
1364 return context;
1365 }
1366
1367 public static ActivityManagerService self() {
1368 return mSelf;
1369 }
1370
1371 static class AThread extends Thread {
1372 ActivityManagerService mService;
1373 boolean mReady = false;
1374
1375 public AThread() {
1376 super("ActivityManager");
1377 }
1378
1379 public void run() {
1380 Looper.prepare();
1381
1382 android.os.Process.setThreadPriority(
1383 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001384 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385
1386 ActivityManagerService m = new ActivityManagerService();
1387
1388 synchronized (this) {
1389 mService = m;
1390 notifyAll();
1391 }
1392
1393 synchronized (this) {
1394 while (!mReady) {
1395 try {
1396 wait();
1397 } catch (InterruptedException e) {
1398 }
1399 }
1400 }
1401
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001402 // For debug builds, log event loop stalls to dropbox for analysis.
1403 if (StrictMode.conditionallyEnableDebugLogging()) {
1404 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1405 }
1406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 Looper.loop();
1408 }
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 static class MemBinder extends Binder {
1412 ActivityManagerService mActivityManagerService;
1413 MemBinder(ActivityManagerService activityManagerService) {
1414 mActivityManagerService = activityManagerService;
1415 }
1416
1417 @Override
1418 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001419 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1420 != PackageManager.PERMISSION_GRANTED) {
1421 pw.println("Permission Denial: can't dump meminfo from from pid="
1422 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1423 + " without permission " + android.Manifest.permission.DUMP);
1424 return;
1425 }
1426
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001427 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001428 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430 }
1431
Chet Haase9c1e23b2011-03-24 10:51:31 -07001432 static class GraphicsBinder extends Binder {
1433 ActivityManagerService mActivityManagerService;
1434 GraphicsBinder(ActivityManagerService activityManagerService) {
1435 mActivityManagerService = activityManagerService;
1436 }
1437
1438 @Override
1439 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001440 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1441 != PackageManager.PERMISSION_GRANTED) {
1442 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1443 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1444 + " without permission " + android.Manifest.permission.DUMP);
1445 return;
1446 }
1447
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001448 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001449 }
1450 }
1451
Jeff Brown6754ba22011-12-14 20:20:01 -08001452 static class DbBinder extends Binder {
1453 ActivityManagerService mActivityManagerService;
1454 DbBinder(ActivityManagerService activityManagerService) {
1455 mActivityManagerService = activityManagerService;
1456 }
1457
1458 @Override
1459 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1460 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1461 != PackageManager.PERMISSION_GRANTED) {
1462 pw.println("Permission Denial: can't dump dbinfo from from pid="
1463 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1464 + " without permission " + android.Manifest.permission.DUMP);
1465 return;
1466 }
1467
1468 mActivityManagerService.dumpDbInfo(fd, pw, args);
1469 }
1470 }
1471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 static class CpuBinder extends Binder {
1473 ActivityManagerService mActivityManagerService;
1474 CpuBinder(ActivityManagerService activityManagerService) {
1475 mActivityManagerService = activityManagerService;
1476 }
1477
1478 @Override
1479 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001480 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1481 != PackageManager.PERMISSION_GRANTED) {
1482 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1483 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1484 + " without permission " + android.Manifest.permission.DUMP);
1485 return;
1486 }
1487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001489 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1490 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1491 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493 }
1494 }
1495
1496 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001497 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001498
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001499 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1500 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1501 mBroadcastQueues[0] = mFgBroadcastQueue;
1502 mBroadcastQueues[1] = mBgBroadcastQueue;
1503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 File dataDir = Environment.getDataDirectory();
1505 File systemDir = new File(dataDir, "system");
1506 systemDir.mkdirs();
1507 mBatteryStatsService = new BatteryStatsService(new File(
1508 systemDir, "batterystats.bin").toString());
1509 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001510 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001511 mOnBattery = DEBUG_POWER ? true
1512 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001513 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001515 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001516 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001517 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Jack Palevichb90d28c2009-07-22 15:35:24 -07001519 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1520 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1521
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001522 mConfiguration.setToDefaults();
1523 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001524 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 mProcessStats.init();
1526
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001527 mCompatModePackages = new CompatModePackages(this, systemDir);
1528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 // Add ourself to the Watchdog monitors.
1530 Watchdog.getInstance().addMonitor(this);
1531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 mProcessStatsThread = new Thread("ProcessStats") {
1533 public void run() {
1534 while (true) {
1535 try {
1536 try {
1537 synchronized(this) {
1538 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001539 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001541 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 // + ", write delay=" + nextWriteDelay);
1543 if (nextWriteDelay < nextCpuDelay) {
1544 nextCpuDelay = nextWriteDelay;
1545 }
1546 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001547 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 this.wait(nextCpuDelay);
1549 }
1550 }
1551 } catch (InterruptedException e) {
1552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 updateCpuStatsNow();
1554 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557 }
1558 }
1559 };
1560 mProcessStatsThread.start();
1561 }
1562
1563 @Override
1564 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1565 throws RemoteException {
1566 try {
1567 return super.onTransact(code, data, reply, flags);
1568 } catch (RuntimeException e) {
1569 // The activity manager only throws security exceptions, so let's
1570 // log all others.
1571 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001572 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574 throw e;
1575 }
1576 }
1577
1578 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001579 final long now = SystemClock.uptimeMillis();
1580 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1581 return;
1582 }
1583 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1584 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 mProcessStatsThread.notify();
1586 }
1587 }
1588 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 void updateCpuStatsNow() {
1591 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001592 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 final long now = SystemClock.uptimeMillis();
1594 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001597 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1598 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 haveNewCpuStats = true;
1600 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 //Slog.i(TAG, mProcessStats.printCurrentState());
1602 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 // + mProcessStats.getTotalCpuPercent() + "%");
1604
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 if ("true".equals(SystemProperties.get("events.cpu"))) {
1607 int user = mProcessStats.getLastUserTime();
1608 int system = mProcessStats.getLastSystemTime();
1609 int iowait = mProcessStats.getLastIoWaitTime();
1610 int irq = mProcessStats.getLastIrqTime();
1611 int softIrq = mProcessStats.getLastSoftIrqTime();
1612 int idle = mProcessStats.getLastIdleTime();
1613
1614 int total = user + system + iowait + irq + softIrq + idle;
1615 if (total == 0) total = 1;
1616
Doug Zongker2bec3d42009-12-04 12:52:44 -08001617 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 ((user+system+iowait+irq+softIrq) * 100) / total,
1619 (user * 100) / total,
1620 (system * 100) / total,
1621 (iowait * 100) / total,
1622 (irq * 100) / total,
1623 (softIrq * 100) / total);
1624 }
1625 }
1626
Amith Yamasanie43530a2009-08-21 13:11:37 -07001627 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001628 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001629 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 synchronized(mPidsSelfLocked) {
1631 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001632 if (mOnBattery) {
1633 int perc = bstats.startAddingCpuLocked();
1634 int totalUTime = 0;
1635 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001636 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001638 ProcessStats.Stats st = mProcessStats.getStats(i);
1639 if (!st.working) {
1640 continue;
1641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001643 int otherUTime = (st.rel_utime*perc)/100;
1644 int otherSTime = (st.rel_stime*perc)/100;
1645 totalUTime += otherUTime;
1646 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (pr != null) {
1648 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001649 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1650 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001651 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001652 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001653 } else {
1654 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001655 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001656 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001657 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1658 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001659 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
1662 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001663 bstats.finishAddingCpuLocked(perc, totalUTime,
1664 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
1667 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1670 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001671 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 }
1674 }
1675 }
1676
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001677 @Override
1678 public void batteryNeedsCpuUpdate() {
1679 updateCpuStatsNow();
1680 }
1681
1682 @Override
1683 public void batteryPowerChanged(boolean onBattery) {
1684 // When plugging in, update the CPU stats first before changing
1685 // the plug state.
1686 updateCpuStatsNow();
1687 synchronized (this) {
1688 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001689 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001690 }
1691 }
1692 }
1693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 /**
1695 * Initialize the application bind args. These are passed to each
1696 * process when the bindApplication() IPC is sent to the process. They're
1697 * lazily setup to make sure the services are running when they're asked for.
1698 */
1699 private HashMap<String, IBinder> getCommonServicesLocked() {
1700 if (mAppBindArgs == null) {
1701 mAppBindArgs = new HashMap<String, IBinder>();
1702
1703 // Setup the application init args
1704 mAppBindArgs.put("package", ServiceManager.getService("package"));
1705 mAppBindArgs.put("window", ServiceManager.getService("window"));
1706 mAppBindArgs.put(Context.ALARM_SERVICE,
1707 ServiceManager.getService(Context.ALARM_SERVICE));
1708 }
1709 return mAppBindArgs;
1710 }
1711
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001712 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (mFocusedActivity != r) {
1714 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001715 if (r != null) {
1716 mWindowManager.setFocusedApp(r.appToken, true);
1717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
1719 }
1720
Dianne Hackborn906497c2010-05-10 15:57:38 -07001721 private final void updateLruProcessInternalLocked(ProcessRecord app,
1722 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001724 int lrui = mLruProcesses.indexOf(app);
1725 if (lrui >= 0) mLruProcesses.remove(lrui);
1726
1727 int i = mLruProcesses.size()-1;
1728 int skipTop = 0;
1729
Dianne Hackborn906497c2010-05-10 15:57:38 -07001730 app.lruSeq = mLruSeq;
1731
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001732 // compute the new weight for this process.
1733 if (updateActivityTime) {
1734 app.lastActivityTime = SystemClock.uptimeMillis();
1735 }
1736 if (app.activities.size() > 0) {
1737 // If this process has activities, we more strongly want to keep
1738 // it around.
1739 app.lruWeight = app.lastActivityTime;
1740 } else if (app.pubProviders.size() > 0) {
1741 // If this process contains content providers, we want to keep
1742 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001743 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001744 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001745 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001746 } else {
1747 // If this process doesn't have activities, we less strongly
1748 // want to keep it around, and generally want to avoid getting
1749 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001750 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001751 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001752 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001753 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001754
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001755 while (i >= 0) {
1756 ProcessRecord p = mLruProcesses.get(i);
1757 // If this app shouldn't be in front of the first N background
1758 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001759 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001760 skipTop--;
1761 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001762 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001763 mLruProcesses.add(i+1, app);
1764 break;
1765 }
1766 i--;
1767 }
1768 if (i < 0) {
1769 mLruProcesses.add(0, app);
1770 }
1771
Dianne Hackborn906497c2010-05-10 15:57:38 -07001772 // If the app is currently using a content provider or service,
1773 // bump those processes as well.
1774 if (app.connections.size() > 0) {
1775 for (ConnectionRecord cr : app.connections) {
1776 if (cr.binding != null && cr.binding.service != null
1777 && cr.binding.service.app != null
1778 && cr.binding.service.app.lruSeq != mLruSeq) {
1779 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1780 updateActivityTime, i+1);
1781 }
1782 }
1783 }
1784 if (app.conProviders.size() > 0) {
1785 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001786 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1787 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001788 updateActivityTime, i+1);
1789 }
1790 }
1791 }
1792
Joe Onorato8a9b2202010-02-26 18:56:32 -08001793 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 if (oomAdj) {
1795 updateOomAdjLocked();
1796 }
1797 }
1798
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001799 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001800 boolean oomAdj, boolean updateActivityTime) {
1801 mLruSeq++;
1802 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1803 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001804
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001805 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 String processName, int uid) {
1807 if (uid == Process.SYSTEM_UID) {
1808 // The system gets to run in any process. If there are multiple
1809 // processes with the same uid, just pick the first (this
1810 // should never happen).
1811 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1812 processName);
1813 return procs != null ? procs.valueAt(0) : null;
1814 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001815 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 ProcessRecord proc = mProcessNames.get(processName, uid);
1817 return proc;
1818 }
1819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001821 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001822 try {
1823 if (pm.performDexOpt(packageName)) {
1824 mDidDexOpt = true;
1825 }
1826 } catch (RemoteException e) {
1827 }
1828 }
1829
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001830 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 int transit = mWindowManager.getPendingAppTransition();
1832 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1833 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1834 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1835 }
1836
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001837 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001839 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1840 boolean isolated) {
1841 ProcessRecord app;
1842 if (!isolated) {
1843 app = getProcessRecordLocked(processName, info.uid);
1844 } else {
1845 // If this is an isolated process, it can't re-use an existing process.
1846 app = null;
1847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 // We don't have to do anything more if:
1849 // (1) There is an existing application record; and
1850 // (2) The caller doesn't think it is dead, OR there is no thread
1851 // object attached to it so we know it couldn't have crashed; and
1852 // (3) There is a pid assigned to it, so it is either starting or
1853 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001854 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 + " app=" + app + " knownToBeDead=" + knownToBeDead
1856 + " thread=" + (app != null ? app.thread : null)
1857 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001858 if (app != null && app.pid > 0) {
1859 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001860 // We already have the app running, or are waiting for it to
1861 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001862 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001863 // If this is a new package in the process, add the package to the list
1864 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001865 return app;
1866 } else {
1867 // An application record is attached to a previous process,
1868 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001869 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001870 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 String hostingNameStr = hostingName != null
1875 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001876
1877 if (!isolated) {
1878 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1879 // If we are in the background, then check to see if this process
1880 // is bad. If so, we will just silently fail.
1881 if (mBadProcesses.get(info.processName, info.uid) != null) {
1882 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1883 + "/" + info.processName);
1884 return null;
1885 }
1886 } else {
1887 // When the user is explicitly starting a process, then clear its
1888 // crash count so that we won't make it bad until they see at
1889 // least one crash dialog again, and make the process good again
1890 // if it had been bad.
1891 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001892 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001893 mProcessCrashTimes.remove(info.processName, info.uid);
1894 if (mBadProcesses.get(info.processName, info.uid) != null) {
1895 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1896 info.processName);
1897 mBadProcesses.remove(info.processName, info.uid);
1898 if (app != null) {
1899 app.bad = false;
1900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902 }
1903 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001906 app = newProcessRecordLocked(null, info, processName, isolated);
1907 if (app == null) {
1908 Slog.w(TAG, "Failed making new process record for "
1909 + processName + "/" + info.uid + " isolated=" + isolated);
1910 return null;
1911 }
1912 mProcessNames.put(processName, app.uid, app);
1913 if (isolated) {
1914 mIsolatedProcesses.put(app.uid, app);
1915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 } else {
1917 // If this is a new package in the process, add the package to the list
1918 app.addPackage(info.packageName);
1919 }
1920
1921 // If the system is not ready yet, then hold off on starting this
1922 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001923 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001924 && !isAllowedWhileBooting(info)
1925 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 if (!mProcessesOnHold.contains(app)) {
1927 mProcessesOnHold.add(app);
1928 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001929 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 return app;
1931 }
1932
1933 startProcessLocked(app, hostingType, hostingNameStr);
1934 return (app.pid != 0) ? app : null;
1935 }
1936
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001937 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1938 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1939 }
1940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 private final void startProcessLocked(ProcessRecord app,
1942 String hostingType, String hostingNameStr) {
1943 if (app.pid > 0 && app.pid != MY_PID) {
1944 synchronized (mPidsSelfLocked) {
1945 mPidsSelfLocked.remove(app.pid);
1946 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1947 }
1948 app.pid = 0;
1949 }
1950
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001951 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1952 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 mProcessesOnHold.remove(app);
1954
1955 updateCpuStats();
1956
1957 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1958 mProcDeaths[0] = 0;
1959
1960 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001961 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001964 if (!app.isolated) {
1965 try {
1966 gids = mContext.getPackageManager().getPackageGids(
1967 app.info.packageName);
1968 } catch (PackageManager.NameNotFoundException e) {
1969 Slog.w(TAG, "Unable to retrieve gids", e);
1970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
1972 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1973 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1974 && mTopComponent != null
1975 && app.processName.equals(mTopComponent.getPackageName())) {
1976 uid = 0;
1977 }
1978 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1979 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1980 uid = 0;
1981 }
1982 }
1983 int debugFlags = 0;
1984 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1985 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001986 // Also turn on CheckJNI for debuggable apps. It's quite
1987 // awkward to turn on otherwise.
1988 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001990 // Run the app in safe mode if its manifest requests so or the
1991 // system is booted in safe mode.
1992 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1993 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001994 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1997 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1998 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001999 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2000 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 if ("1".equals(SystemProperties.get("debug.assert"))) {
2003 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2004 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002005
2006 // Start the process. It will either succeed and return a result containing
2007 // the PID of the new process, or else throw a RuntimeException.
2008 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002009 app.processName, uid, uid, gids, debugFlags,
2010 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2013 synchronized (bs) {
2014 if (bs.isOnBattery()) {
2015 app.batteryStats.incStartsLocked();
2016 }
2017 }
2018
Jeff Brown3f9dd282011-07-08 20:02:19 -07002019 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 app.processName, hostingType,
2021 hostingNameStr != null ? hostingNameStr : "");
2022
2023 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002024 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
2026
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002027 StringBuilder buf = mStringBuilder;
2028 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 buf.append("Start proc ");
2030 buf.append(app.processName);
2031 buf.append(" for ");
2032 buf.append(hostingType);
2033 if (hostingNameStr != null) {
2034 buf.append(" ");
2035 buf.append(hostingNameStr);
2036 }
2037 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002038 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 buf.append(" uid=");
2040 buf.append(uid);
2041 buf.append(" gids={");
2042 if (gids != null) {
2043 for (int gi=0; gi<gids.length; gi++) {
2044 if (gi != 0) buf.append(", ");
2045 buf.append(gids[gi]);
2046
2047 }
2048 }
2049 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002050 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002051 app.pid = startResult.pid;
2052 app.usingWrapper = startResult.usingWrapper;
2053 app.removed = false;
2054 synchronized (mPidsSelfLocked) {
2055 this.mPidsSelfLocked.put(startResult.pid, app);
2056 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2057 msg.obj = app;
2058 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2059 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 } catch (RuntimeException e) {
2062 // XXX do better error recovery.
2063 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002064 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 }
2066 }
2067
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002068 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 if (resumed) {
2070 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2071 } else {
2072 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2073 }
2074 }
2075
Amith Yamasani742a6712011-05-04 14:49:28 -07002076 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002077 if (mHeadless) {
2078 // Added because none of the other calls to ensureBootCompleted seem to fire
2079 // when running headless.
2080 ensureBootCompleted();
2081 return false;
2082 }
2083
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002084 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2085 && mTopAction == null) {
2086 // We are running in factory test mode, but unable to find
2087 // the factory test app, so just sit around displaying the
2088 // error message and don't try to start anything.
2089 return false;
2090 }
2091 Intent intent = new Intent(
2092 mTopAction,
2093 mTopData != null ? Uri.parse(mTopData) : null);
2094 intent.setComponent(mTopComponent);
2095 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2096 intent.addCategory(Intent.CATEGORY_HOME);
2097 }
2098 ActivityInfo aInfo =
2099 intent.resolveActivityInfo(mContext.getPackageManager(),
2100 STOCK_PM_FLAGS);
2101 if (aInfo != null) {
2102 intent.setComponent(new ComponentName(
2103 aInfo.applicationInfo.packageName, aInfo.name));
2104 // Don't do this if the home app is currently being
2105 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002106 aInfo = new ActivityInfo(aInfo);
2107 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002108 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2109 aInfo.applicationInfo.uid);
2110 if (app == null || app.instrumentationClass == null) {
2111 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002112 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002113 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002114 }
2115 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002116
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002117 return true;
2118 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002119
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002120 /**
2121 * Starts the "new version setup screen" if appropriate.
2122 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002123 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002124 // Only do this once per boot.
2125 if (mCheckedForSetup) {
2126 return;
2127 }
2128
2129 // We will show this screen if the current one is a different
2130 // version than the last one shown, and we are not running in
2131 // low-level factory test mode.
2132 final ContentResolver resolver = mContext.getContentResolver();
2133 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2134 Settings.Secure.getInt(resolver,
2135 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2136 mCheckedForSetup = true;
2137
2138 // See if we should be showing the platform update setup UI.
2139 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2140 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2141 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2142
2143 // We don't allow third party apps to replace this.
2144 ResolveInfo ri = null;
2145 for (int i=0; ris != null && i<ris.size(); i++) {
2146 if ((ris.get(i).activityInfo.applicationInfo.flags
2147 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2148 ri = ris.get(i);
2149 break;
2150 }
2151 }
2152
2153 if (ri != null) {
2154 String vers = ri.activityInfo.metaData != null
2155 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2156 : null;
2157 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2158 vers = ri.activityInfo.applicationInfo.metaData.getString(
2159 Intent.METADATA_SETUP_VERSION);
2160 }
2161 String lastVers = Settings.Secure.getString(
2162 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2163 if (vers != null && !vers.equals(lastVers)) {
2164 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2165 intent.setComponent(new ComponentName(
2166 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002167 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002168 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002169 }
2170 }
2171 }
2172 }
2173
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002174 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002175 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002176 }
2177
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002178 void enforceNotIsolatedCaller(String caller) {
2179 if (UserId.isIsolated(Binder.getCallingUid())) {
2180 throw new SecurityException("Isolated process not allowed to call " + caller);
2181 }
2182 }
2183
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002184 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002185 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002186 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002187 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2188 }
2189 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002190
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002192 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2193 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 synchronized (this) {
2195 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2196 }
2197 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002198
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002199 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002200 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002201 synchronized (this) {
2202 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2203 }
2204 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002205
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002206 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002207 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2208 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002209 synchronized (this) {
2210 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002211 }
2212 }
2213
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002214 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002215 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002216 synchronized (this) {
2217 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2218 }
2219 }
2220
2221 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002222 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2223 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002224 synchronized (this) {
2225 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2226 }
2227 }
2228
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002229 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002230 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002231
2232 final int identHash = System.identityHashCode(r);
2233 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235
Jeff Sharkeya4620792011-05-20 15:29:23 -07002236 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2237 int i = mProcessObservers.beginBroadcast();
2238 while (i > 0) {
2239 i--;
2240 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2241 if (observer != null) {
2242 try {
2243 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2244 } catch (RemoteException e) {
2245 }
2246 }
2247 }
2248 mProcessObservers.finishBroadcast();
2249 }
2250
2251 private void dispatchProcessDied(int pid, int uid) {
2252 int i = mProcessObservers.beginBroadcast();
2253 while (i > 0) {
2254 i--;
2255 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2256 if (observer != null) {
2257 try {
2258 observer.onProcessDied(pid, uid);
2259 } catch (RemoteException e) {
2260 }
2261 }
2262 }
2263 mProcessObservers.finishBroadcast();
2264 }
2265
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002266 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002267 final int N = mPendingActivityLaunches.size();
2268 if (N <= 0) {
2269 return;
2270 }
2271 for (int i=0; i<N; i++) {
2272 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002273 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002274 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2275 doResume && i == (N-1));
2276 }
2277 mPendingActivityLaunches.clear();
2278 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002279
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002280 public final int startActivity(IApplicationThread caller,
2281 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2282 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002283 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2284 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002285 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002286 int userId = 0;
2287 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2288 // Requesting home, set the identity to the current user
2289 // HACK!
2290 userId = mCurrentUserId;
2291 } else {
2292 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2293 // the current user's userId
2294 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2295 userId = 0;
2296 } else {
2297 userId = Binder.getOrigCallingUser();
2298 }
2299 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002300 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07002301 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
2302 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002303 }
2304
2305 public final WaitResult startActivityAndWait(IApplicationThread caller,
2306 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2307 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002308 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2309 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002310 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002311 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002312 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002313 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002314 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002315 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002317 return res;
2318 }
2319
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002320 public final int startActivityWithConfig(IApplicationThread caller,
2321 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2322 int grantedMode, IBinder resultTo,
2323 String resultWho, int requestCode, boolean onlyIfNeeded,
2324 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002325 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002326 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002327 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07002328 requestCode, onlyIfNeeded,
2329 debug, null, null, false, null, config, Binder.getOrigCallingUser());
2330 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002331 }
2332
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002333 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002334 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002335 IBinder resultTo, String resultWho, int requestCode,
2336 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002337 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002338 // Refuse possible leaked file descriptors
2339 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2340 throw new IllegalArgumentException("File descriptors passed in Intent");
2341 }
2342
2343 IIntentSender sender = intent.getTarget();
2344 if (!(sender instanceof PendingIntentRecord)) {
2345 throw new IllegalArgumentException("Bad PendingIntent object");
2346 }
2347
2348 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002349
2350 synchronized (this) {
2351 // If this is coming from the currently resumed activity, it is
2352 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002353 if (mMainStack.mResumedActivity != null
2354 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002355 Binder.getCallingUid()) {
2356 mAppSwitchesAllowedTime = 0;
2357 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002358 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002359 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002360 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07002361 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002362 }
2363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 public boolean startNextMatchingActivity(IBinder callingActivity,
2365 Intent intent) {
2366 // Refuse possible leaked file descriptors
2367 if (intent != null && intent.hasFileDescriptors() == true) {
2368 throw new IllegalArgumentException("File descriptors passed in Intent");
2369 }
2370
2371 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002372 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2373 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 return false;
2375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 if (r.app == null || r.app.thread == null) {
2377 // The caller is not running... d'oh!
2378 return false;
2379 }
2380 intent = new Intent(intent);
2381 // The caller is not allowed to change the data.
2382 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2383 // And we are resetting to find the next component...
2384 intent.setComponent(null);
2385
2386 ActivityInfo aInfo = null;
2387 try {
2388 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002389 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002391 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392
2393 // Look for the original activity in the list...
2394 final int N = resolves != null ? resolves.size() : 0;
2395 for (int i=0; i<N; i++) {
2396 ResolveInfo rInfo = resolves.get(i);
2397 if (rInfo.activityInfo.packageName.equals(r.packageName)
2398 && rInfo.activityInfo.name.equals(r.info.name)) {
2399 // We found the current one... the next matching is
2400 // after it.
2401 i++;
2402 if (i<N) {
2403 aInfo = resolves.get(i).activityInfo;
2404 }
2405 break;
2406 }
2407 }
2408 } catch (RemoteException e) {
2409 }
2410
2411 if (aInfo == null) {
2412 // Nobody who is next!
2413 return false;
2414 }
2415
2416 intent.setComponent(new ComponentName(
2417 aInfo.applicationInfo.packageName, aInfo.name));
2418 intent.setFlags(intent.getFlags()&~(
2419 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2420 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2421 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2422 Intent.FLAG_ACTIVITY_NEW_TASK));
2423
2424 // Okay now we need to start the new activity, replacing the
2425 // currently running activity. This is a little tricky because
2426 // we want to start the new one as if the current one is finished,
2427 // but not finish the current one first so that there is no flicker.
2428 // And thus...
2429 final boolean wasFinishing = r.finishing;
2430 r.finishing = true;
2431
2432 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002433 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 final String resultWho = r.resultWho;
2435 final int requestCode = r.requestCode;
2436 r.resultTo = null;
2437 if (resultTo != null) {
2438 resultTo.removeResultsLocked(r, resultWho, requestCode);
2439 }
2440
2441 final long origId = Binder.clearCallingIdentity();
2442 // XXX we are not dealing with propagating grantedUriPermissions...
2443 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002444 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002445 r.resolvedType, null, 0, aInfo,
2446 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002447 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 Binder.restoreCallingIdentity(origId);
2449
2450 r.finishing = wasFinishing;
2451 if (res != START_SUCCESS) {
2452 return false;
2453 }
2454 return true;
2455 }
2456 }
2457
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002458 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 Intent intent, String resolvedType, IBinder resultTo,
2460 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002461
2462 // This is so super not safe, that only the system (or okay root)
2463 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002464 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002465 final int callingUid = Binder.getCallingUid();
2466 if (callingUid != 0 && callingUid != Process.myUid()) {
2467 throw new SecurityException(
2468 "startActivityInPackage only available to the system");
2469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470
Amith Yamasani742a6712011-05-04 14:49:28 -07002471 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002472 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07002473 null, null, false, null, null, userId);
2474 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002475 }
2476
2477 public final int startActivities(IApplicationThread caller,
2478 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002479 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002480 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
2481 Binder.getOrigCallingUser());
2482 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002483 }
2484
2485 public final int startActivitiesInPackage(int uid,
2486 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2487
2488 // This is so super not safe, that only the system (or okay root)
2489 // can do it.
2490 final int callingUid = Binder.getCallingUid();
2491 if (callingUid != 0 && callingUid != Process.myUid()) {
2492 throw new SecurityException(
2493 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002495 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
2496 UserId.getUserId(uid));
2497 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
2499
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002502 // Quick case: check if the top-most recent task is the same.
2503 if (N > 0 && mRecentTasks.get(0) == task) {
2504 return;
2505 }
2506 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 for (int i=0; i<N; i++) {
2508 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002509 if (task.userId == tr.userId
2510 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2511 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 mRecentTasks.remove(i);
2513 i--;
2514 N--;
2515 if (task.intent == null) {
2516 // If the new recent task we are adding is not fully
2517 // specified, then replace it with the existing recent task.
2518 task = tr;
2519 }
2520 }
2521 }
2522 if (N >= MAX_RECENT_TASKS) {
2523 mRecentTasks.remove(N-1);
2524 }
2525 mRecentTasks.add(0, task);
2526 }
2527
2528 public void setRequestedOrientation(IBinder token,
2529 int requestedOrientation) {
2530 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002531 ActivityRecord r = mMainStack.isInStackLocked(token);
2532 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 return;
2534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002536 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002538 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002539 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 if (config != null) {
2541 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002542 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002543 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 }
2545 }
2546 Binder.restoreCallingIdentity(origId);
2547 }
2548 }
2549
2550 public int getRequestedOrientation(IBinder token) {
2551 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002552 ActivityRecord r = mMainStack.isInStackLocked(token);
2553 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2555 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002556 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 }
2558 }
2559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 /**
2561 * This is the internal entry point for handling Activity.finish().
2562 *
2563 * @param token The Binder token referencing the Activity we want to finish.
2564 * @param resultCode Result code, if any, from this Activity.
2565 * @param resultData Result data (Intent), if any, from this Activity.
2566 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002567 * @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 -08002568 */
2569 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2570 // Refuse possible leaked file descriptors
2571 if (resultData != null && resultData.hasFileDescriptors() == true) {
2572 throw new IllegalArgumentException("File descriptors passed in Intent");
2573 }
2574
2575 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002576 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002578 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 if (next != null) {
2580 // ask watcher if this is allowed
2581 boolean resumeOK = true;
2582 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002583 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002585 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587
2588 if (!resumeOK) {
2589 return false;
2590 }
2591 }
2592 }
2593 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002594 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 resultData, "app-request");
2596 Binder.restoreCallingIdentity(origId);
2597 return res;
2598 }
2599 }
2600
Dianne Hackborn860755f2010-06-03 18:47:52 -07002601 public final void finishHeavyWeightApp() {
2602 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2603 != PackageManager.PERMISSION_GRANTED) {
2604 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2605 + Binder.getCallingPid()
2606 + ", uid=" + Binder.getCallingUid()
2607 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2608 Slog.w(TAG, msg);
2609 throw new SecurityException(msg);
2610 }
2611
2612 synchronized(this) {
2613 if (mHeavyWeightProcess == null) {
2614 return;
2615 }
2616
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002617 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002618 mHeavyWeightProcess.activities);
2619 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002620 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002621 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002622 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002623 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002624 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002625 null, "finish-heavy");
2626 }
2627 }
2628 }
2629
2630 mHeavyWeightProcess = null;
2631 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2632 }
2633 }
2634
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002635 public void crashApplication(int uid, int initialPid, String packageName,
2636 String message) {
2637 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2638 != PackageManager.PERMISSION_GRANTED) {
2639 String msg = "Permission Denial: crashApplication() from pid="
2640 + Binder.getCallingPid()
2641 + ", uid=" + Binder.getCallingUid()
2642 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2643 Slog.w(TAG, msg);
2644 throw new SecurityException(msg);
2645 }
2646
2647 synchronized(this) {
2648 ProcessRecord proc = null;
2649
2650 // Figure out which process to kill. We don't trust that initialPid
2651 // still has any relation to current pids, so must scan through the
2652 // list.
2653 synchronized (mPidsSelfLocked) {
2654 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2655 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002656 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002657 continue;
2658 }
2659 if (p.pid == initialPid) {
2660 proc = p;
2661 break;
2662 }
2663 for (String str : p.pkgList) {
2664 if (str.equals(packageName)) {
2665 proc = p;
2666 }
2667 }
2668 }
2669 }
2670
2671 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002672 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002673 + " initialPid=" + initialPid
2674 + " packageName=" + packageName);
2675 return;
2676 }
2677
2678 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002679 if (proc.pid == Process.myPid()) {
2680 Log.w(TAG, "crashApplication: trying to crash self!");
2681 return;
2682 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002683 long ident = Binder.clearCallingIdentity();
2684 try {
2685 proc.thread.scheduleCrash(message);
2686 } catch (RemoteException e) {
2687 }
2688 Binder.restoreCallingIdentity(ident);
2689 }
2690 }
2691 }
2692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 public final void finishSubActivity(IBinder token, String resultWho,
2694 int requestCode) {
2695 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002696 ActivityRecord self = mMainStack.isInStackLocked(token);
2697 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 return;
2699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700
2701 final long origId = Binder.clearCallingIdentity();
2702
2703 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002704 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2705 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 if (r.resultTo == self && r.requestCode == requestCode) {
2707 if ((r.resultWho == null && resultWho == null) ||
2708 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002709 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 Activity.RESULT_CANCELED, null, "request-sub");
2711 }
2712 }
2713 }
2714
2715 Binder.restoreCallingIdentity(origId);
2716 }
2717 }
2718
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002719 public boolean willActivityBeVisible(IBinder token) {
2720 synchronized(this) {
2721 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002722 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2723 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002724 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002725 return true;
2726 }
2727 if (r.fullscreen && !r.finishing) {
2728 return false;
2729 }
2730 }
2731 return true;
2732 }
2733 }
2734
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002735 public void overridePendingTransition(IBinder token, String packageName,
2736 int enterAnim, int exitAnim) {
2737 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002738 ActivityRecord self = mMainStack.isInStackLocked(token);
2739 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002740 return;
2741 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002742
2743 final long origId = Binder.clearCallingIdentity();
2744
2745 if (self.state == ActivityState.RESUMED
2746 || self.state == ActivityState.PAUSING) {
2747 mWindowManager.overridePendingAppTransition(packageName,
2748 enterAnim, exitAnim);
2749 }
2750
2751 Binder.restoreCallingIdentity(origId);
2752 }
2753 }
2754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 * Main function for removing an existing process from the activity manager
2757 * as a result of that process going away. Clears out all connections
2758 * to the process.
2759 */
2760 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002761 boolean restarting, boolean allowRestart) {
2762 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002764 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 }
2766
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002767 if (mProfileProc == app) {
2768 clearProfilerLocked();
2769 }
2770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 // Just in case...
Dianne Hackborncbb722e2012-02-07 18:33:49 -08002772 mMainStack.appDiedLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773
2774 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002775 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776
2777 boolean atTop = true;
2778 boolean hasVisibleActivities = false;
2779
2780 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002781 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002782 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 TAG, "Removing app " + app + " from history with " + i + " entries");
2784 while (i > 0) {
2785 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002786 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002787 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2789 if (r.app == app) {
2790 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002791 if (ActivityStack.DEBUG_ADD_REMOVE) {
2792 RuntimeException here = new RuntimeException("here");
2793 here.fillInStackTrace();
2794 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2795 + ": haveState=" + r.haveState
2796 + " stateNotNeeded=" + r.stateNotNeeded
2797 + " finishing=" + r.finishing
2798 + " state=" + r.state, here);
2799 }
2800 if (!r.finishing) {
2801 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002802 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2803 System.identityHashCode(r),
2804 r.task.taskId, r.shortComponentName,
2805 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002806 }
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08002807 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002808 mMainStack.mHistory.remove(i);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002809 r.takeFromHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002810 mWindowManager.removeAppToken(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002812 mMainStack.validateAppTokensLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002814 r.removeUriPermissionsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815
2816 } else {
2817 // We have the current state for this activity, so
2818 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002819 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 TAG, "Keeping entry, setting app to null");
2821 if (r.visible) {
2822 hasVisibleActivities = true;
2823 }
2824 r.app = null;
2825 r.nowVisible = false;
2826 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002827 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2828 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 r.icicle = null;
2830 }
2831 }
2832
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002833 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 }
2835 atTop = false;
2836 }
2837
2838 app.activities.clear();
2839
2840 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002841 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 + " running instrumentation " + app.instrumentationClass);
2843 Bundle info = new Bundle();
2844 info.putString("shortMsg", "Process crashed.");
2845 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2846 }
2847
2848 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002849 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 // If there was nothing to resume, and we are not already
2851 // restarting this process, but there is a visible activity that
2852 // is hosted by the process... then make sure all visible
2853 // activities are running, taking care of restarting this
2854 // process.
2855 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002856 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858 }
2859 }
2860 }
2861
2862 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2863 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002865 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2866 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2868 return i;
2869 }
2870 }
2871 return -1;
2872 }
2873
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002874 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 IApplicationThread thread) {
2876 if (thread == null) {
2877 return null;
2878 }
2879
2880 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002881 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 }
2883
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002884 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 IApplicationThread thread) {
2886
2887 mProcDeaths[0]++;
2888
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002889 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2890 synchronized (stats) {
2891 stats.noteProcessDiedLocked(app.info.uid, pid);
2892 }
2893
Magnus Edlund7bb25812010-02-24 15:45:06 +01002894 // Clean up already done if the process has been re-started.
2895 if (app.pid == pid && app.thread != null &&
2896 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002897 if (!app.killedBackground) {
2898 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2899 + ") has died.");
2900 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002901 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002902 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 TAG, "Dying app: " + app + ", pid: " + pid
2904 + ", thread: " + thread.asBinder());
2905 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002906 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907
2908 if (doLowMem) {
2909 // If there are no longer any background processes running,
2910 // and the app that died was not running instrumentation,
2911 // then tell everyone we are now low on memory.
2912 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002913 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2914 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002915 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 haveBg = true;
2917 break;
2918 }
2919 }
2920
2921 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002922 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002923 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002924 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2925 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002926 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002927 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2928 // The low memory report is overriding any current
2929 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002930 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002931 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002932 rec.lastRequestedGc = 0;
2933 } else {
2934 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002936 rec.reportLowMemory = true;
2937 rec.lastLowMemory = now;
2938 mProcessesToGc.remove(rec);
2939 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002942 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002943 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002946 } else if (app.pid != pid) {
2947 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002948 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002949 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002950 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002951 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002952 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 + thread.asBinder());
2954 }
2955 }
2956
Dan Egnor42471dd2010-01-07 17:25:22 -08002957 /**
2958 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002959 * @param clearTraces causes the dump file to be erased prior to the new
2960 * traces being written, if true; when false, the new traces will be
2961 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002962 * @param firstPids of dalvik VM processes to dump stack traces for first
2963 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002964 * @return file containing stack traces, or null if no dump file is configured
2965 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002966 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2967 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002968 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2969 if (tracesPath == null || tracesPath.length() == 0) {
2970 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002972
2973 File tracesFile = new File(tracesPath);
2974 try {
2975 File tracesDir = tracesFile.getParentFile();
2976 if (!tracesDir.exists()) tracesFile.mkdirs();
2977 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2978
Christopher Tate6ee412d2010-05-28 12:01:56 -07002979 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002980 tracesFile.createNewFile();
2981 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2982 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002983 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002984 return null;
2985 }
2986
2987 // Use a FileObserver to detect when traces finish writing.
2988 // The order of traces is considered important to maintain for legibility.
2989 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2990 public synchronized void onEvent(int event, String path) { notify(); }
2991 };
2992
2993 try {
2994 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002995
2996 // First collect all of the stacks of the most important pids.
2997 try {
2998 int num = firstPids.size();
2999 for (int i = 0; i < num; i++) {
3000 synchronized (observer) {
3001 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3002 observer.wait(200); // Wait for write-close, give up after 200msec
3003 }
3004 }
3005 } catch (InterruptedException e) {
3006 Log.wtf(TAG, e);
3007 }
3008
3009 // Next measure CPU usage.
3010 if (processStats != null) {
3011 processStats.init();
3012 System.gc();
3013 processStats.update();
3014 try {
3015 synchronized (processStats) {
3016 processStats.wait(500); // measure over 1/2 second.
3017 }
3018 } catch (InterruptedException e) {
3019 }
3020 processStats.update();
3021
3022 // We'll take the stack crawls of just the top apps using CPU.
3023 final int N = processStats.countWorkingStats();
3024 int numProcs = 0;
3025 for (int i=0; i<N && numProcs<5; i++) {
3026 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3027 if (lastPids.indexOfKey(stats.pid) >= 0) {
3028 numProcs++;
3029 try {
3030 synchronized (observer) {
3031 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3032 observer.wait(200); // Wait for write-close, give up after 200msec
3033 }
3034 } catch (InterruptedException e) {
3035 Log.wtf(TAG, e);
3036 }
3037
3038 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003039 }
3040 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003041
3042 return tracesFile;
3043
Dan Egnor42471dd2010-01-07 17:25:22 -08003044 } finally {
3045 observer.stopWatching();
3046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 }
3048
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003049 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3050 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003051 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3052 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3053
Dianne Hackborn287952c2010-09-22 22:34:31 -07003054 if (mController != null) {
3055 try {
3056 // 0 == continue, -1 = kill process immediately
3057 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3058 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3059 } catch (RemoteException e) {
3060 mController = null;
3061 }
3062 }
3063
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003064 long anrTime = SystemClock.uptimeMillis();
3065 if (MONITOR_CPU_USAGE) {
3066 updateCpuStatsNow();
3067 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003068
3069 synchronized (this) {
3070 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3071 if (mShuttingDown) {
3072 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3073 return;
3074 } else if (app.notResponding) {
3075 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3076 return;
3077 } else if (app.crashing) {
3078 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3079 return;
3080 }
3081
3082 // In case we come through here for the same app before completing
3083 // this one, mark as anring now so we will bail out.
3084 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003085
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003086 // Log the ANR to the event log.
3087 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3088 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003089
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003090 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003091 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003092
3093 int parentPid = app.pid;
3094 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003095 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003096
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003097 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003098
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003099 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3100 ProcessRecord r = mLruProcesses.get(i);
3101 if (r != null && r.thread != null) {
3102 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003103 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3104 if (r.persistent) {
3105 firstPids.add(pid);
3106 } else {
3107 lastPids.put(pid, Boolean.TRUE);
3108 }
3109 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
3112 }
3113
Dan Egnor42471dd2010-01-07 17:25:22 -08003114 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003115 StringBuilder info = mStringBuilder;
3116 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003117 info.append("ANR in ").append(app.processName);
3118 if (activity != null && activity.shortComponentName != null) {
3119 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003120 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003121 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003123 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003125 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003126 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128
Dianne Hackborn287952c2010-09-22 22:34:31 -07003129 final ProcessStats processStats = new ProcessStats(true);
3130
3131 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3132
Dan Egnor42471dd2010-01-07 17:25:22 -08003133 String cpuInfo = null;
3134 if (MONITOR_CPU_USAGE) {
3135 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003136 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003137 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003138 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003139 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003140 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 }
3142
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003143 info.append(processStats.printCurrentState(anrTime));
3144
Joe Onorato8a9b2202010-02-26 18:56:32 -08003145 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003146 if (tracesFile == null) {
3147 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3148 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3149 }
3150
Jeff Sharkeya353d262011-10-28 11:12:06 -07003151 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3152 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003153
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003154 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003156 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3157 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003159 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3160 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 }
3162 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003163 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 }
3165 }
3166
Dan Egnor42471dd2010-01-07 17:25:22 -08003167 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3168 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3169 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003170
3171 synchronized (this) {
3172 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003173 Slog.w(TAG, "Killing " + app + ": background ANR");
3174 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3175 app.processName, app.setAdj, "background ANR");
3176 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003177 return;
3178 }
3179
3180 // Set the app's notResponding state, and look up the errorReportReceiver
3181 makeAppNotRespondingLocked(app,
3182 activity != null ? activity.shortComponentName : null,
3183 annotation != null ? "ANR " + annotation : "ANR",
3184 info.toString());
3185
3186 // Bring up the infamous App Not Responding dialog
3187 Message msg = Message.obtain();
3188 HashMap map = new HashMap();
3189 msg.what = SHOW_NOT_RESPONDING_MSG;
3190 msg.obj = map;
3191 map.put("app", app);
3192 if (activity != null) {
3193 map.put("activity", activity);
3194 }
3195
3196 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
3199
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003200 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3201 if (!mLaunchWarningShown) {
3202 mLaunchWarningShown = true;
3203 mHandler.post(new Runnable() {
3204 @Override
3205 public void run() {
3206 synchronized (ActivityManagerService.this) {
3207 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3208 d.show();
3209 mHandler.postDelayed(new Runnable() {
3210 @Override
3211 public void run() {
3212 synchronized (ActivityManagerService.this) {
3213 d.dismiss();
3214 mLaunchWarningShown = false;
3215 }
3216 }
3217 }, 4000);
3218 }
3219 }
3220 });
3221 }
3222 }
3223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003225 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003226 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 int uid = Binder.getCallingUid();
3228 int pid = Binder.getCallingPid();
3229 long callingId = Binder.clearCallingIdentity();
3230 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003231 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 int pkgUid = -1;
3233 synchronized(this) {
3234 try {
3235 pkgUid = pm.getPackageUid(packageName);
3236 } catch (RemoteException e) {
3237 }
3238 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003239 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 return false;
3241 }
3242 if (uid == pkgUid || checkComponentPermission(
3243 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003244 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003246 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 } else {
3248 throw new SecurityException(pid+" does not have permission:"+
3249 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3250 "for process:"+packageName);
3251 }
3252 }
3253
3254 try {
3255 //clear application user data
3256 pm.clearApplicationUserData(packageName, observer);
3257 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3258 Uri.fromParts("package", packageName, null));
3259 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003260 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003261 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 } catch (RemoteException e) {
3263 }
3264 } finally {
3265 Binder.restoreCallingIdentity(callingId);
3266 }
3267 return true;
3268 }
3269
Dianne Hackborn03abb812010-01-04 18:43:19 -08003270 public void killBackgroundProcesses(final String packageName) {
3271 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3272 != PackageManager.PERMISSION_GRANTED &&
3273 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3274 != PackageManager.PERMISSION_GRANTED) {
3275 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 + Binder.getCallingPid()
3277 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003278 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003279 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 throw new SecurityException(msg);
3281 }
3282
3283 long callingId = Binder.clearCallingIdentity();
3284 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003285 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 int pkgUid = -1;
3287 synchronized(this) {
3288 try {
3289 pkgUid = pm.getPackageUid(packageName);
3290 } catch (RemoteException e) {
3291 }
3292 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003293 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 return;
3295 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003296 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003297 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3298 }
3299 } finally {
3300 Binder.restoreCallingIdentity(callingId);
3301 }
3302 }
3303
3304 public void killAllBackgroundProcesses() {
3305 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3306 != PackageManager.PERMISSION_GRANTED) {
3307 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3308 + Binder.getCallingPid()
3309 + ", uid=" + Binder.getCallingUid()
3310 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3311 Slog.w(TAG, msg);
3312 throw new SecurityException(msg);
3313 }
3314
3315 long callingId = Binder.clearCallingIdentity();
3316 try {
3317 synchronized(this) {
3318 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3319 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3320 final int NA = apps.size();
3321 for (int ia=0; ia<NA; ia++) {
3322 ProcessRecord app = apps.valueAt(ia);
3323 if (app.persistent) {
3324 // we don't kill persistent processes
3325 continue;
3326 }
3327 if (app.removed) {
3328 procs.add(app);
3329 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3330 app.removed = true;
3331 procs.add(app);
3332 }
3333 }
3334 }
3335
3336 int N = procs.size();
3337 for (int i=0; i<N; i++) {
3338 removeProcessLocked(procs.get(i), false, true, "kill all background");
3339 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003340 }
3341 } finally {
3342 Binder.restoreCallingIdentity(callingId);
3343 }
3344 }
3345
3346 public void forceStopPackage(final String packageName) {
3347 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3348 != PackageManager.PERMISSION_GRANTED) {
3349 String msg = "Permission Denial: forceStopPackage() from pid="
3350 + Binder.getCallingPid()
3351 + ", uid=" + Binder.getCallingUid()
3352 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003353 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003354 throw new SecurityException(msg);
3355 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003356 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003357 long callingId = Binder.clearCallingIdentity();
3358 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003359 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003360 int pkgUid = -1;
3361 synchronized(this) {
3362 try {
3363 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003364 // Convert the uid to the one for the calling user
3365 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003366 } catch (RemoteException e) {
3367 }
3368 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003369 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003370 return;
3371 }
3372 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003373 try {
3374 pm.setPackageStoppedState(packageName, true);
3375 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003376 } catch (IllegalArgumentException e) {
3377 Slog.w(TAG, "Failed trying to unstop package "
3378 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
3381 } finally {
3382 Binder.restoreCallingIdentity(callingId);
3383 }
3384 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003385
3386 /*
3387 * The pkg name and uid have to be specified.
3388 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3389 */
3390 public void killApplicationWithUid(String pkg, int uid) {
3391 if (pkg == null) {
3392 return;
3393 }
3394 // Make sure the uid is valid.
3395 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003396 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003397 return;
3398 }
3399 int callerUid = Binder.getCallingUid();
3400 // Only the system server can kill an application
3401 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003402 // Post an aysnc message to kill the application
3403 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3404 msg.arg1 = uid;
3405 msg.arg2 = 0;
3406 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003407 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003408 } else {
3409 throw new SecurityException(callerUid + " cannot kill pkg: " +
3410 pkg);
3411 }
3412 }
3413
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003414 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003415 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003416 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003417 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003418 if (reason != null) {
3419 intent.putExtra("reason", reason);
3420 }
3421
3422 final int uid = Binder.getCallingUid();
3423 final long origId = Binder.clearCallingIdentity();
3424 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003425 mWindowManager.closeSystemDialogs(reason);
3426
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003427 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003428 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003429 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003430 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003431 Activity.RESULT_CANCELED, null, "close-sys");
3432 }
3433 }
3434
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003435 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003436 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003437 }
3438 Binder.restoreCallingIdentity(origId);
3439 }
3440
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003441 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003442 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003443 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003444 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3445 for (int i=pids.length-1; i>=0; i--) {
3446 infos[i] = new Debug.MemoryInfo();
3447 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003448 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003449 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003450 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003451
Dianne Hackbornb437e092011-08-05 17:50:29 -07003452 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003453 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003454 long[] pss = new long[pids.length];
3455 for (int i=pids.length-1; i>=0; i--) {
3456 pss[i] = Debug.getPss(pids[i]);
3457 }
3458 return pss;
3459 }
3460
Christopher Tate5e1ab332009-09-01 20:32:49 -07003461 public void killApplicationProcess(String processName, int uid) {
3462 if (processName == null) {
3463 return;
3464 }
3465
3466 int callerUid = Binder.getCallingUid();
3467 // Only the system server can kill an application
3468 if (callerUid == Process.SYSTEM_UID) {
3469 synchronized (this) {
3470 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003471 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003472 try {
3473 app.thread.scheduleSuicide();
3474 } catch (RemoteException e) {
3475 // If the other end already died, then our work here is done.
3476 }
3477 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003478 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003479 + processName + " / " + uid);
3480 }
3481 }
3482 } else {
3483 throw new SecurityException(callerUid + " cannot kill app process: " +
3484 processName);
3485 }
3486 }
3487
Dianne Hackborn03abb812010-01-04 18:43:19 -08003488 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003489 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3491 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003492 if (!mProcessesReady) {
3493 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 intent.putExtra(Intent.EXTRA_UID, uid);
3496 broadcastIntentLocked(null, null, intent,
3497 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003498 false, false,
3499 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 }
3501
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003502 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003503 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003504 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003505 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506
Dianne Hackborn03abb812010-01-04 18:43:19 -08003507 // Remove all processes this package may have touched: all with the
3508 // same UID (except for the system or root user), and all whose name
3509 // matches the package name.
3510 final String procNamePrefix = packageName + ":";
3511 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3512 final int NA = apps.size();
3513 for (int ia=0; ia<NA; ia++) {
3514 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003515 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003516 // we don't kill persistent processes
3517 continue;
3518 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003519 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003520 if (doit) {
3521 procs.add(app);
3522 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003523 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3524 || app.processName.equals(packageName)
3525 || app.processName.startsWith(procNamePrefix)) {
3526 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003527 if (!doit) {
3528 return true;
3529 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003530 app.removed = true;
3531 procs.add(app);
3532 }
3533 }
3534 }
3535 }
3536
3537 int N = procs.size();
3538 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003539 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003540 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003541 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003542 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003543
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003544 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003545 boolean callerWillRestart, boolean purgeCache, boolean doit,
3546 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003547 int i;
3548 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 if (uid < 0) {
3551 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003552 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 } catch (RemoteException e) {
3554 }
3555 }
3556
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003557 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003558 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003559
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003560 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3561 while (badApps.hasNext()) {
3562 SparseArray<Long> ba = badApps.next();
3563 if (ba.get(uid) != null) {
3564 badApps.remove();
3565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
3567 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003568
3569 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003570 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003572 TaskRecord lastTask = null;
3573 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003574 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003575 final boolean samePackage = r.packageName.equals(name);
3576 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003577 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003578 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003579 if (r.finishing) {
3580 // If this activity is just finishing, then it is not
3581 // interesting as far as something to stop.
3582 continue;
3583 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003584 return true;
3585 }
3586 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003587 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003588 if (samePackage) {
3589 if (r.app != null) {
3590 r.app.removed = true;
3591 }
3592 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003594 lastTask = r.task;
3595 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3596 null, "force-stop")) {
3597 i--;
3598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 }
3600 }
3601
3602 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003603 int userId = UserId.getUserId(uid);
3604 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003605 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003606 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003607 if (!doit) {
3608 return true;
3609 }
3610 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003611 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 if (service.app != null) {
3613 service.app.removed = true;
3614 }
3615 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003616 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 services.add(service);
3618 }
3619 }
3620
3621 N = services.size();
3622 for (i=0; i<N; i++) {
3623 bringDownServiceLocked(services.get(i), true);
3624 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003625
3626 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
3627 for (ContentProviderRecord provider : mProvidersByClass.values()) {
3628 if (provider.info.packageName.equals(name)
3629 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3630 if (!doit) {
3631 return true;
3632 }
3633 didSomething = true;
3634 providers.add(provider);
3635 }
3636 }
3637
3638 N = providers.size();
3639 for (i=0; i<N; i++) {
3640 removeDyingProviderLocked(null, providers.get(i));
3641 }
3642
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643 if (doit) {
3644 if (purgeCache) {
3645 AttributeCache ac = AttributeCache.instance();
3646 if (ac != null) {
3647 ac.removePackage(name);
3648 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003649 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003650 if (mBooted) {
3651 mMainStack.resumeTopActivityLocked(null);
3652 mMainStack.scheduleIdleLocked();
3653 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003654 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003655
3656 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 }
3658
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003659 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003660 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003662 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003663 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003664 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 + "/" + uid + ")");
3666
3667 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003668 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003669 if (mHeavyWeightProcess == app) {
3670 mHeavyWeightProcess = null;
3671 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 boolean needRestart = false;
3674 if (app.pid > 0 && app.pid != MY_PID) {
3675 int pid = app.pid;
3676 synchronized (mPidsSelfLocked) {
3677 mPidsSelfLocked.remove(pid);
3678 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3679 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003680 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003681 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003682 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003683 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003685 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003687 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 } else {
3689 needRestart = true;
3690 }
3691 }
3692 } else {
3693 mRemovedProcesses.add(app);
3694 }
3695
3696 return needRestart;
3697 }
3698
3699 private final void processStartTimedOutLocked(ProcessRecord app) {
3700 final int pid = app.pid;
3701 boolean gone = false;
3702 synchronized (mPidsSelfLocked) {
3703 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3704 if (knownApp != null && knownApp.thread == null) {
3705 mPidsSelfLocked.remove(pid);
3706 gone = true;
3707 }
3708 }
3709
3710 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003711 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003712 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003713 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003714 mProcessNames.remove(app.processName, app.uid);
3715 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003716 if (mHeavyWeightProcess == app) {
3717 mHeavyWeightProcess = null;
3718 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3719 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003720 // Take care of any launching providers waiting for this process.
3721 checkAppInLaunchingProvidersLocked(app, true);
3722 // Take care of any services that are waiting for the process.
3723 for (int i=0; i<mPendingServices.size(); i++) {
3724 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003725 if ((app.uid == sr.appInfo.uid
3726 && app.processName.equals(sr.processName))
3727 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003728 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003729 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003730 mPendingServices.remove(i);
3731 i--;
3732 bringDownServiceLocked(sr, true);
3733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003735 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3736 app.processName, app.setAdj, "start timeout");
3737 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003738 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003739 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003740 try {
3741 IBackupManager bm = IBackupManager.Stub.asInterface(
3742 ServiceManager.getService(Context.BACKUP_SERVICE));
3743 bm.agentDisconnected(app.info.packageName);
3744 } catch (RemoteException e) {
3745 // Can't happen; the backup manager is local
3746 }
3747 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003748 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003749 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003750 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003753 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 }
3755 }
3756
3757 private final boolean attachApplicationLocked(IApplicationThread thread,
3758 int pid) {
3759
3760 // Find the application record that is being attached... either via
3761 // the pid if we are running in multiple processes, or just pull the
3762 // next app record if we are emulating process with anonymous threads.
3763 ProcessRecord app;
3764 if (pid != MY_PID && pid >= 0) {
3765 synchronized (mPidsSelfLocked) {
3766 app = mPidsSelfLocked.get(pid);
3767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003768 } else {
3769 app = null;
3770 }
3771
3772 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003773 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003775 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003777 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 } else {
3779 try {
3780 thread.scheduleExit();
3781 } catch (Exception e) {
3782 // Ignore exceptions.
3783 }
3784 }
3785 return false;
3786 }
3787
3788 // If this application record is still attached to a previous
3789 // process, clean it up now.
3790 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003791 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 }
3793
3794 // Tell the process all about itself.
3795
Joe Onorato8a9b2202010-02-26 18:56:32 -08003796 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 TAG, "Binding process pid " + pid + " to record " + app);
3798
3799 String processName = app.processName;
3800 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003801 AppDeathRecipient adr = new AppDeathRecipient(
3802 app, pid, thread);
3803 thread.asBinder().linkToDeath(adr, 0);
3804 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 } catch (RemoteException e) {
3806 app.resetPackageList();
3807 startProcessLocked(app, "link fail", processName);
3808 return false;
3809 }
3810
Doug Zongker2bec3d42009-12-04 12:52:44 -08003811 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812
3813 app.thread = thread;
3814 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003815 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3816 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 app.forcingToForeground = null;
3818 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003819 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 app.debugging = false;
3821
3822 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3823
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003824 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003825 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003827 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003828 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003829 }
3830
Joe Onorato8a9b2202010-02-26 18:56:32 -08003831 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 TAG, "New app record " + app
3833 + " thread=" + thread.asBinder() + " pid=" + pid);
3834 try {
3835 int testMode = IApplicationThread.DEBUG_OFF;
3836 if (mDebugApp != null && mDebugApp.equals(processName)) {
3837 testMode = mWaitForDebugger
3838 ? IApplicationThread.DEBUG_WAIT
3839 : IApplicationThread.DEBUG_ON;
3840 app.debugging = true;
3841 if (mDebugTransient) {
3842 mDebugApp = mOrigDebugApp;
3843 mWaitForDebugger = mOrigWaitForDebugger;
3844 }
3845 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003846 String profileFile = app.instrumentationProfileFile;
3847 ParcelFileDescriptor profileFd = null;
3848 boolean profileAutoStop = false;
3849 if (mProfileApp != null && mProfileApp.equals(processName)) {
3850 mProfileProc = app;
3851 profileFile = mProfileFile;
3852 profileFd = mProfileFd;
3853 profileAutoStop = mAutoStopProfiler;
3854 }
3855
Christopher Tate181fafa2009-05-14 11:12:14 -07003856 // If the app is being launched for restore or full backup, set it up specially
3857 boolean isRestrictedBackupMode = false;
3858 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3859 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003860 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003861 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3862 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003863
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003864 ensurePackageDexOpt(app.instrumentationInfo != null
3865 ? app.instrumentationInfo.packageName
3866 : app.info.packageName);
3867 if (app.instrumentationClass != null) {
3868 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003869 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003870 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003871 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003872 ApplicationInfo appInfo = app.instrumentationInfo != null
3873 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003874 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003875 if (profileFd != null) {
3876 profileFd = profileFd.dup();
3877 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003878 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003879 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003881 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003882 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003883 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003884 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003885 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 } catch (Exception e) {
3887 // todo: Yikes! What should we do? For now we will try to
3888 // start another process, but that could easily get us in
3889 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003890 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891
3892 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003893 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 startProcessLocked(app, "bind fail", processName);
3895 return false;
3896 }
3897
3898 // Remove this record from the list of starting applications.
3899 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003900 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3901 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 mProcessesOnHold.remove(app);
3903
3904 boolean badApp = false;
3905 boolean didSomething = false;
3906
3907 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003909 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003910 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 && processName.equals(hr.processName)) {
3912 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003913 if (mHeadless) {
3914 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3915 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 didSomething = true;
3917 }
3918 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003919 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 + hr.intent.getComponent().flattenToShortString(), e);
3921 badApp = true;
3922 }
3923 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003924 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 }
3926 }
3927
3928 // Find any services that should be running in this process...
3929 if (!badApp && mPendingServices.size() > 0) {
3930 ServiceRecord sr = null;
3931 try {
3932 for (int i=0; i<mPendingServices.size(); i++) {
3933 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003934 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3935 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 continue;
3937 }
3938
3939 mPendingServices.remove(i);
3940 i--;
3941 realStartServiceLocked(sr, app);
3942 didSomething = true;
3943 }
3944 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003945 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 + sr.shortName, e);
3947 badApp = true;
3948 }
3949 }
3950
Christopher Tatef46723b2012-01-26 14:19:24 -08003951 // Check if a next-broadcast receiver is in this process...
3952 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003954 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003956 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 }
3959 }
3960
Christopher Tate181fafa2009-05-14 11:12:14 -07003961 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003962 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003963 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003964 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003965 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003966 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3967 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3968 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003969 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003970 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003971 e.printStackTrace();
3972 }
3973 }
3974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 if (badApp) {
3976 // todo: Also need to kill application to deal with all
3977 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003978 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 return false;
3980 }
3981
3982 if (!didSomething) {
3983 updateOomAdjLocked();
3984 }
3985
3986 return true;
3987 }
3988
3989 public final void attachApplication(IApplicationThread thread) {
3990 synchronized (this) {
3991 int callingPid = Binder.getCallingPid();
3992 final long origId = Binder.clearCallingIdentity();
3993 attachApplicationLocked(thread, callingPid);
3994 Binder.restoreCallingIdentity(origId);
3995 }
3996 }
3997
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003998 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004000 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4001 if (stopProfiling) {
4002 synchronized (this) {
4003 if (mProfileProc == r.app) {
4004 if (mProfileFd != null) {
4005 try {
4006 mProfileFd.close();
4007 } catch (IOException e) {
4008 }
4009 clearProfilerLocked();
4010 }
4011 }
4012 }
4013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 Binder.restoreCallingIdentity(origId);
4015 }
4016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004019 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 mWindowManager.enableScreenAfterBoot();
4021 }
4022
Dianne Hackborn661cd522011-08-22 00:26:20 -07004023 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004024 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004025 mWindowManager.showBootMessage(msg, always);
4026 }
4027
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004028 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004029 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004030 synchronized (this) {
4031 mMainStack.dismissKeyguardOnNextActivityLocked();
4032 }
4033 }
4034
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004035 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004036 IntentFilter pkgFilter = new IntentFilter();
4037 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4038 pkgFilter.addDataScheme("package");
4039 mContext.registerReceiver(new BroadcastReceiver() {
4040 @Override
4041 public void onReceive(Context context, Intent intent) {
4042 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4043 if (pkgs != null) {
4044 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004045 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004046 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004047 setResultCode(Activity.RESULT_OK);
4048 return;
4049 }
4050 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004051 }
4052 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004053 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004054 }, pkgFilter);
4055
4056 synchronized (this) {
4057 // Ensure that any processes we had put on hold are now started
4058 // up.
4059 final int NP = mProcessesOnHold.size();
4060 if (NP > 0) {
4061 ArrayList<ProcessRecord> procs =
4062 new ArrayList<ProcessRecord>(mProcessesOnHold);
4063 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004064 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4065 + procs.get(ip));
4066 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004067 }
4068 }
4069
4070 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004071 // Start looking for apps that are abusing wake locks.
4072 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004073 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004074 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004075 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004076 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004077 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004078 broadcastIntentLocked(null, null,
4079 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4080 null, null, 0, null, null,
4081 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004082 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004083 }
4084 }
4085 }
4086
4087 final void ensureBootCompleted() {
4088 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004089 boolean enableScreen;
4090 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004091 booting = mBooting;
4092 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004093 enableScreen = !mBooted;
4094 mBooted = true;
4095 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004096
4097 if (booting) {
4098 finishBooting();
4099 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004100
4101 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004102 enableScreenAfterBoot();
4103 }
4104 }
4105
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004106 public final void activityPaused(IBinder token) {
4107 final long origId = Binder.clearCallingIdentity();
4108 mMainStack.activityPaused(token, false);
4109 Binder.restoreCallingIdentity(origId);
4110 }
4111
4112 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4113 CharSequence description) {
4114 if (localLOGV) Slog.v(
4115 TAG, "Activity stopped: token=" + token);
4116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 // Refuse possible leaked file descriptors
4118 if (icicle != null && icicle.hasFileDescriptors()) {
4119 throw new IllegalArgumentException("File descriptors passed in Bundle");
4120 }
4121
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004122 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123
4124 final long origId = Binder.clearCallingIdentity();
4125
4126 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004127 r = mMainStack.isInStackLocked(token);
4128 if (r != null) {
4129 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 }
4131 }
4132
4133 if (r != null) {
4134 sendPendingThumbnail(r, null, null, null, false);
4135 }
4136
4137 trimApplications();
4138
4139 Binder.restoreCallingIdentity(origId);
4140 }
4141
4142 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004143 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004144 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 }
4146
4147 public String getCallingPackage(IBinder token) {
4148 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004149 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004150 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 }
4152 }
4153
4154 public ComponentName getCallingActivity(IBinder token) {
4155 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004156 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 return r != null ? r.intent.getComponent() : null;
4158 }
4159 }
4160
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004161 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004162 ActivityRecord r = mMainStack.isInStackLocked(token);
4163 if (r == null) {
4164 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004166 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 }
4168
4169 public ComponentName getActivityClassForToken(IBinder token) {
4170 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004171 ActivityRecord r = mMainStack.isInStackLocked(token);
4172 if (r == null) {
4173 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004175 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 }
4177 }
4178
4179 public String getPackageForToken(IBinder token) {
4180 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004181 ActivityRecord r = mMainStack.isInStackLocked(token);
4182 if (r == null) {
4183 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004185 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 }
4187 }
4188
4189 public IIntentSender getIntentSender(int type,
4190 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004191 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004192 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004194 if (intents != null) {
4195 if (intents.length < 1) {
4196 throw new IllegalArgumentException("Intents array length must be >= 1");
4197 }
4198 for (int i=0; i<intents.length; i++) {
4199 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004200 if (intent != null) {
4201 if (intent.hasFileDescriptors()) {
4202 throw new IllegalArgumentException("File descriptors passed in Intent");
4203 }
4204 if (type == INTENT_SENDER_BROADCAST &&
4205 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4206 throw new IllegalArgumentException(
4207 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4208 }
4209 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004210 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004211 }
4212 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004213 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004214 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004215 }
4216 }
4217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 synchronized(this) {
4219 int callingUid = Binder.getCallingUid();
4220 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004221 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004222 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004224 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 String msg = "Permission Denial: getIntentSender() from pid="
4226 + Binder.getCallingPid()
4227 + ", uid=" + Binder.getCallingUid()
4228 + ", (need uid=" + uid + ")"
4229 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004230 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 throw new SecurityException(msg);
4232 }
4233 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004234
Amith Yamasani742a6712011-05-04 14:49:28 -07004235 if (DEBUG_MU)
4236 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4237 + Binder.getOrigCallingUid());
4238 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004239 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 } catch (RemoteException e) {
4242 throw new SecurityException(e);
4243 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004244 }
4245 }
4246
4247 IIntentSender getIntentSenderLocked(int type,
4248 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004249 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004250 if (DEBUG_MU)
4251 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004252 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004253 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004254 activity = mMainStack.isInStackLocked(token);
4255 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004256 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004258 if (activity.finishing) {
4259 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004261 }
4262
4263 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4264 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4265 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4266 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4267 |PendingIntent.FLAG_UPDATE_CURRENT);
4268
4269 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4270 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004271 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004272 WeakReference<PendingIntentRecord> ref;
4273 ref = mIntentSenderRecords.get(key);
4274 PendingIntentRecord rec = ref != null ? ref.get() : null;
4275 if (rec != null) {
4276 if (!cancelCurrent) {
4277 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004278 if (rec.key.requestIntent != null) {
4279 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4280 }
4281 if (intents != null) {
4282 intents[intents.length-1] = rec.key.requestIntent;
4283 rec.key.allIntents = intents;
4284 rec.key.allResolvedTypes = resolvedTypes;
4285 } else {
4286 rec.key.allIntents = null;
4287 rec.key.allResolvedTypes = null;
4288 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 return rec;
4291 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004292 rec.canceled = true;
4293 mIntentSenderRecords.remove(key);
4294 }
4295 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 return rec;
4297 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004298 rec = new PendingIntentRecord(this, key, callingUid);
4299 mIntentSenderRecords.put(key, rec.ref);
4300 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4301 if (activity.pendingResults == null) {
4302 activity.pendingResults
4303 = new HashSet<WeakReference<PendingIntentRecord>>();
4304 }
4305 activity.pendingResults.add(rec.ref);
4306 }
4307 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 }
4309
4310 public void cancelIntentSender(IIntentSender sender) {
4311 if (!(sender instanceof PendingIntentRecord)) {
4312 return;
4313 }
4314 synchronized(this) {
4315 PendingIntentRecord rec = (PendingIntentRecord)sender;
4316 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004317 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 .getPackageUid(rec.key.packageName);
4319 if (uid != Binder.getCallingUid()) {
4320 String msg = "Permission Denial: cancelIntentSender() from pid="
4321 + Binder.getCallingPid()
4322 + ", uid=" + Binder.getCallingUid()
4323 + " is not allowed to cancel packges "
4324 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004325 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 throw new SecurityException(msg);
4327 }
4328 } catch (RemoteException e) {
4329 throw new SecurityException(e);
4330 }
4331 cancelIntentSenderLocked(rec, true);
4332 }
4333 }
4334
4335 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4336 rec.canceled = true;
4337 mIntentSenderRecords.remove(rec.key);
4338 if (cleanActivity && rec.key.activity != null) {
4339 rec.key.activity.pendingResults.remove(rec.ref);
4340 }
4341 }
4342
4343 public String getPackageForIntentSender(IIntentSender pendingResult) {
4344 if (!(pendingResult instanceof PendingIntentRecord)) {
4345 return null;
4346 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004347 try {
4348 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4349 return res.key.packageName;
4350 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 }
4352 return null;
4353 }
4354
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004355 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4356 if (!(pendingResult instanceof PendingIntentRecord)) {
4357 return false;
4358 }
4359 try {
4360 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4361 if (res.key.allIntents == null) {
4362 return false;
4363 }
4364 for (int i=0; i<res.key.allIntents.length; i++) {
4365 Intent intent = res.key.allIntents[i];
4366 if (intent.getPackage() != null && intent.getComponent() != null) {
4367 return false;
4368 }
4369 }
4370 return true;
4371 } catch (ClassCastException e) {
4372 }
4373 return false;
4374 }
4375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 public void setProcessLimit(int max) {
4377 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4378 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004379 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004380 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004381 mProcessLimitOverride = max;
4382 }
4383 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 }
4385
4386 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004387 synchronized (this) {
4388 return mProcessLimitOverride;
4389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 }
4391
4392 void foregroundTokenDied(ForegroundToken token) {
4393 synchronized (ActivityManagerService.this) {
4394 synchronized (mPidsSelfLocked) {
4395 ForegroundToken cur
4396 = mForegroundProcesses.get(token.pid);
4397 if (cur != token) {
4398 return;
4399 }
4400 mForegroundProcesses.remove(token.pid);
4401 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4402 if (pr == null) {
4403 return;
4404 }
4405 pr.forcingToForeground = null;
4406 pr.foregroundServices = false;
4407 }
4408 updateOomAdjLocked();
4409 }
4410 }
4411
4412 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4413 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4414 "setProcessForeground()");
4415 synchronized(this) {
4416 boolean changed = false;
4417
4418 synchronized (mPidsSelfLocked) {
4419 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004420 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004421 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 return;
4423 }
4424 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4425 if (oldToken != null) {
4426 oldToken.token.unlinkToDeath(oldToken, 0);
4427 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004428 if (pr != null) {
4429 pr.forcingToForeground = null;
4430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431 changed = true;
4432 }
4433 if (isForeground && token != null) {
4434 ForegroundToken newToken = new ForegroundToken() {
4435 public void binderDied() {
4436 foregroundTokenDied(this);
4437 }
4438 };
4439 newToken.pid = pid;
4440 newToken.token = token;
4441 try {
4442 token.linkToDeath(newToken, 0);
4443 mForegroundProcesses.put(pid, newToken);
4444 pr.forcingToForeground = token;
4445 changed = true;
4446 } catch (RemoteException e) {
4447 // If the process died while doing this, we will later
4448 // do the cleanup with the process death link.
4449 }
4450 }
4451 }
4452
4453 if (changed) {
4454 updateOomAdjLocked();
4455 }
4456 }
4457 }
4458
4459 // =========================================================
4460 // PERMISSIONS
4461 // =========================================================
4462
4463 static class PermissionController extends IPermissionController.Stub {
4464 ActivityManagerService mActivityManagerService;
4465 PermissionController(ActivityManagerService activityManagerService) {
4466 mActivityManagerService = activityManagerService;
4467 }
4468
4469 public boolean checkPermission(String permission, int pid, int uid) {
4470 return mActivityManagerService.checkPermission(permission, pid,
4471 uid) == PackageManager.PERMISSION_GRANTED;
4472 }
4473 }
4474
4475 /**
4476 * This can be called with or without the global lock held.
4477 */
4478 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004479 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 // We might be performing an operation on behalf of an indirect binder
4481 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4482 // client identity accordingly before proceeding.
4483 Identity tlsIdentity = sCallerIdentity.get();
4484 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004485 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4487 uid = tlsIdentity.uid;
4488 pid = tlsIdentity.pid;
4489 }
4490
4491 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004492 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 return PackageManager.PERMISSION_GRANTED;
4494 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004495 // Isolated processes don't get any permissions.
4496 if (UserId.isIsolated(uid)) {
4497 return PackageManager.PERMISSION_DENIED;
4498 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004499 // If there is a uid that owns whatever is being accessed, it has
4500 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004501 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004502 return PackageManager.PERMISSION_GRANTED;
4503 }
4504 // If the target is not exported, then nobody else can get to it.
4505 if (!exported) {
4506 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 return PackageManager.PERMISSION_DENIED;
4508 }
4509 if (permission == null) {
4510 return PackageManager.PERMISSION_GRANTED;
4511 }
4512 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004513 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 .checkUidPermission(permission, uid);
4515 } catch (RemoteException e) {
4516 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004517 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 }
4519 return PackageManager.PERMISSION_DENIED;
4520 }
4521
4522 /**
4523 * As the only public entry point for permissions checking, this method
4524 * can enforce the semantic that requesting a check on a null global
4525 * permission is automatically denied. (Internally a null permission
4526 * string is used when calling {@link #checkComponentPermission} in cases
4527 * when only uid-based security is needed.)
4528 *
4529 * This can be called with or without the global lock held.
4530 */
4531 public int checkPermission(String permission, int pid, int uid) {
4532 if (permission == null) {
4533 return PackageManager.PERMISSION_DENIED;
4534 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004535 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 }
4537
4538 /**
4539 * Binder IPC calls go through the public entry point.
4540 * This can be called with or without the global lock held.
4541 */
4542 int checkCallingPermission(String permission) {
4543 return checkPermission(permission,
4544 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004545 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 }
4547
4548 /**
4549 * This can be called with or without the global lock held.
4550 */
4551 void enforceCallingPermission(String permission, String func) {
4552 if (checkCallingPermission(permission)
4553 == PackageManager.PERMISSION_GRANTED) {
4554 return;
4555 }
4556
4557 String msg = "Permission Denial: " + func + " from pid="
4558 + Binder.getCallingPid()
4559 + ", uid=" + Binder.getCallingUid()
4560 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004561 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 throw new SecurityException(msg);
4563 }
4564
4565 private final boolean checkHoldingPermissionsLocked(IPackageManager pm,
Dianne Hackborn48058e82010-09-27 16:53:23 -07004566 ProviderInfo pi, Uri uri, int uid, int modeFlags) {
4567 boolean readPerm = (modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4568 boolean writePerm = (modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
4569 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4570 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 try {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004572 // Is the component private from the target uid?
4573 final boolean prv = !pi.exported && pi.applicationInfo.uid != uid;
4574
4575 // Acceptable if the there is no read permission needed from the
4576 // target or the target is holding the read permission.
4577 if (!readPerm) {
4578 if ((!prv && pi.readPermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 (pm.checkUidPermission(pi.readPermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004580 == PackageManager.PERMISSION_GRANTED)) {
4581 readPerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 }
4583 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004584
4585 // Acceptable if the there is no write permission needed from the
4586 // target or the target is holding the read permission.
4587 if (!writePerm) {
4588 if (!prv && (pi.writePermission == null) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 (pm.checkUidPermission(pi.writePermission, uid)
Dianne Hackborn48058e82010-09-27 16:53:23 -07004590 == PackageManager.PERMISSION_GRANTED)) {
4591 writePerm = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 }
4593 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004594
4595 // Acceptable if there is a path permission matching the URI that
4596 // the target holds the permission on.
4597 PathPermission[] pps = pi.pathPermissions;
4598 if (pps != null && (!readPerm || !writePerm)) {
4599 final String path = uri.getPath();
4600 int i = pps.length;
4601 while (i > 0 && (!readPerm || !writePerm)) {
4602 i--;
4603 PathPermission pp = pps[i];
4604 if (!readPerm) {
4605 final String pprperm = pp.getReadPermission();
4606 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4607 + pprperm + " for " + pp.getPath()
4608 + ": match=" + pp.match(path)
4609 + " check=" + pm.checkUidPermission(pprperm, uid));
4610 if (pprperm != null && pp.match(path) &&
4611 (pm.checkUidPermission(pprperm, uid)
4612 == PackageManager.PERMISSION_GRANTED)) {
4613 readPerm = true;
4614 }
4615 }
4616 if (!writePerm) {
4617 final String ppwperm = pp.getWritePermission();
4618 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4619 + ppwperm + " for " + pp.getPath()
4620 + ": match=" + pp.match(path)
4621 + " check=" + pm.checkUidPermission(ppwperm, uid));
4622 if (ppwperm != null && pp.match(path) &&
4623 (pm.checkUidPermission(ppwperm, uid)
4624 == PackageManager.PERMISSION_GRANTED)) {
4625 writePerm = true;
4626 }
4627 }
4628 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 } catch (RemoteException e) {
4631 return false;
4632 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004633
4634 return readPerm && writePerm;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 }
4636
4637 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4638 int modeFlags) {
4639 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004640 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 return true;
4642 }
4643 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4644 if (perms == null) return false;
4645 UriPermission perm = perms.get(uri);
4646 if (perm == null) return false;
4647 return (modeFlags&perm.modeFlags) == modeFlags;
4648 }
4649
4650 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004651 enforceNotIsolatedCaller("checkUriPermission");
4652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004653 // Another redirected-binder-call permissions check as in
4654 // {@link checkComponentPermission}.
4655 Identity tlsIdentity = sCallerIdentity.get();
4656 if (tlsIdentity != null) {
4657 uid = tlsIdentity.uid;
4658 pid = tlsIdentity.pid;
4659 }
4660
Amith Yamasani742a6712011-05-04 14:49:28 -07004661 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 // Our own process gets to do everything.
4663 if (pid == MY_PID) {
4664 return PackageManager.PERMISSION_GRANTED;
4665 }
4666 synchronized(this) {
4667 return checkUriPermissionLocked(uri, uid, modeFlags)
4668 ? PackageManager.PERMISSION_GRANTED
4669 : PackageManager.PERMISSION_DENIED;
4670 }
4671 }
4672
Dianne Hackborn39792d22010-08-19 18:01:52 -07004673 /**
4674 * Check if the targetPkg can be granted permission to access uri by
4675 * the callingUid using the given modeFlags. Throws a security exception
4676 * if callingUid is not allowed to do this. Returns the uid of the target
4677 * if the URI permission grant should be performed; returns -1 if it is not
4678 * needed (for example targetPkg already has permission to access the URI).
4679 */
4680 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
4681 Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4683 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4684 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004685 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 }
4687
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004688 if (targetPkg != null) {
4689 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4690 "Checking grant " + targetPkg + " permission to " + uri);
4691 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004692
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004693 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694
4695 // If this is not a content: uri, we can't do anything with it.
4696 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004697 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004698 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004699 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 }
4701
4702 String name = uri.getAuthority();
4703 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004704 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4705 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 if (cpr != null) {
4707 pi = cpr.info;
4708 } else {
4709 try {
4710 pi = pm.resolveContentProvider(name,
4711 PackageManager.GET_URI_PERMISSION_PATTERNS);
4712 } catch (RemoteException ex) {
4713 }
4714 }
4715 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004716 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004717 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 }
4719
4720 int targetUid;
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004721 if (targetPkg != null) {
4722 try {
4723 targetUid = pm.getPackageUid(targetPkg);
4724 if (targetUid < 0) {
4725 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4726 "Can't grant URI permission no uid for: " + targetPkg);
4727 return -1;
4728 }
4729 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004730 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 }
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004732 } else {
4733 targetUid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 }
4735
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004736 if (targetUid >= 0) {
4737 // First... does the target actually need this permission?
4738 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4739 // No need to grant the target this permission.
4740 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4741 "Target " + targetPkg + " already has full permission to " + uri);
4742 return -1;
4743 }
4744 } else {
4745 // First... there is no target package, so can anyone access it?
4746 boolean allowed = pi.exported;
4747 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4748 if (pi.readPermission != null) {
4749 allowed = false;
4750 }
4751 }
4752 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4753 if (pi.writePermission != null) {
4754 allowed = false;
4755 }
4756 }
4757 if (allowed) {
4758 return -1;
4759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 }
4761
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004762 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763 if (!pi.grantUriPermissions) {
4764 throw new SecurityException("Provider " + pi.packageName
4765 + "/" + pi.name
4766 + " does not allow granting of Uri permissions (uri "
4767 + uri + ")");
4768 }
4769 if (pi.uriPermissionPatterns != null) {
4770 final int N = pi.uriPermissionPatterns.length;
4771 boolean allowed = false;
4772 for (int i=0; i<N; i++) {
4773 if (pi.uriPermissionPatterns[i] != null
4774 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4775 allowed = true;
4776 break;
4777 }
4778 }
4779 if (!allowed) {
4780 throw new SecurityException("Provider " + pi.packageName
4781 + "/" + pi.name
4782 + " does not allow granting of permission to path of Uri "
4783 + uri);
4784 }
4785 }
4786
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004787 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004789 if (callingUid != Process.myUid()) {
4790 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4791 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4792 throw new SecurityException("Uid " + callingUid
4793 + " does not have permission to uri " + uri);
4794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004795 }
4796 }
4797
Dianne Hackborn39792d22010-08-19 18:01:52 -07004798 return targetUid;
4799 }
4800
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004801 public int checkGrantUriPermission(int callingUid, String targetPkg,
4802 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004803 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004804 synchronized(this) {
4805 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4806 }
4807 }
4808
Dianne Hackborn39792d22010-08-19 18:01:52 -07004809 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4810 Uri uri, int modeFlags, UriPermissionOwner owner) {
4811 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4812 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4813 if (modeFlags == 0) {
4814 return;
4815 }
4816
4817 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 // to the uri, and the target doesn't. Let's now give this to
4819 // the target.
4820
Joe Onorato8a9b2202010-02-26 18:56:32 -08004821 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004822 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 HashMap<Uri, UriPermission> targetUris
4825 = mGrantedUriPermissions.get(targetUid);
4826 if (targetUris == null) {
4827 targetUris = new HashMap<Uri, UriPermission>();
4828 mGrantedUriPermissions.put(targetUid, targetUris);
4829 }
4830
4831 UriPermission perm = targetUris.get(uri);
4832 if (perm == null) {
4833 perm = new UriPermission(targetUid, uri);
4834 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004838 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004840 } else {
4841 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4842 perm.readOwners.add(owner);
4843 owner.addReadPermission(perm);
4844 }
4845 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4846 perm.writeOwners.add(owner);
4847 owner.addWritePermission(perm);
4848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004849 }
4850 }
4851
Dianne Hackborn39792d22010-08-19 18:01:52 -07004852 void grantUriPermissionLocked(int callingUid,
4853 String targetPkg, Uri uri, int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004854 if (targetPkg == null) {
4855 throw new NullPointerException("targetPkg");
4856 }
4857
Dianne Hackborn39792d22010-08-19 18:01:52 -07004858 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags);
4859 if (targetUid < 0) {
4860 return;
4861 }
4862
4863 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4864 }
4865
4866 /**
4867 * Like checkGrantUriPermissionLocked, but takes an Intent.
4868 */
4869 int checkGrantUriPermissionFromIntentLocked(int callingUid,
4870 String targetPkg, Intent intent) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004871 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004872 "Checking URI perm to " + (intent != null ? intent.getData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004873 + " from " + intent + "; flags=0x"
4874 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4875
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004876 if (targetPkg == null) {
4877 throw new NullPointerException("targetPkg");
4878 }
4879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 if (intent == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004881 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 }
4883 Uri data = intent.getData();
4884 if (data == null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004885 return -1;
4886 }
4887 return checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4888 intent.getFlags());
4889 }
4890
4891 /**
4892 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4893 */
4894 void grantUriPermissionUncheckedFromIntentLocked(int targetUid,
4895 String targetPkg, Intent intent, UriPermissionOwner owner) {
4896 grantUriPermissionUncheckedLocked(targetUid, targetPkg, intent.getData(),
4897 intent.getFlags(), owner);
4898 }
4899
4900 void grantUriPermissionFromIntentLocked(int callingUid,
4901 String targetPkg, Intent intent, UriPermissionOwner owner) {
4902 int targetUid = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, intent);
4903 if (targetUid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 return;
4905 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004906
4907 grantUriPermissionUncheckedFromIntentLocked(targetUid, targetPkg, intent, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 }
4909
4910 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4911 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004912 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 synchronized(this) {
4914 final ProcessRecord r = getRecordForAppLocked(caller);
4915 if (r == null) {
4916 throw new SecurityException("Unable to find app for caller "
4917 + caller
4918 + " when granting permission to uri " + uri);
4919 }
4920 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004921 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004922 }
4923 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004924 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 }
4926
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004927 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 null);
4929 }
4930 }
4931
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004932 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004933 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4934 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4935 HashMap<Uri, UriPermission> perms
4936 = mGrantedUriPermissions.get(perm.uid);
4937 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004938 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004939 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004940 perms.remove(perm.uri);
4941 if (perms.size() == 0) {
4942 mGrantedUriPermissions.remove(perm.uid);
4943 }
4944 }
4945 }
4946 }
4947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 private void revokeUriPermissionLocked(int callingUid, Uri uri,
4949 int modeFlags) {
4950 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4951 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4952 if (modeFlags == 0) {
4953 return;
4954 }
4955
Joe Onorato8a9b2202010-02-26 18:56:32 -08004956 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004957 "Revoking all granted permissions to " + uri);
4958
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004959 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960
4961 final String authority = uri.getAuthority();
4962 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004963 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
4964 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 if (cpr != null) {
4966 pi = cpr.info;
4967 } else {
4968 try {
4969 pi = pm.resolveContentProvider(authority,
4970 PackageManager.GET_URI_PERMISSION_PATTERNS);
4971 } catch (RemoteException ex) {
4972 }
4973 }
4974 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004975 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 return;
4977 }
4978
4979 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07004980 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 // Right now, if you are not the original owner of the permission,
4982 // you are not allowed to revoke it.
4983 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4984 throw new SecurityException("Uid " + callingUid
4985 + " does not have permission to uri " + uri);
4986 //}
4987 }
4988
4989 // Go through all of the permissions and remove any that match.
4990 final List<String> SEGMENTS = uri.getPathSegments();
4991 if (SEGMENTS != null) {
4992 final int NS = SEGMENTS.size();
4993 int N = mGrantedUriPermissions.size();
4994 for (int i=0; i<N; i++) {
4995 HashMap<Uri, UriPermission> perms
4996 = mGrantedUriPermissions.valueAt(i);
4997 Iterator<UriPermission> it = perms.values().iterator();
4998 toploop:
4999 while (it.hasNext()) {
5000 UriPermission perm = it.next();
5001 Uri targetUri = perm.uri;
5002 if (!authority.equals(targetUri.getAuthority())) {
5003 continue;
5004 }
5005 List<String> targetSegments = targetUri.getPathSegments();
5006 if (targetSegments == null) {
5007 continue;
5008 }
5009 if (targetSegments.size() < NS) {
5010 continue;
5011 }
5012 for (int j=0; j<NS; j++) {
5013 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5014 continue toploop;
5015 }
5016 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005017 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005018 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 perm.clearModes(modeFlags);
5020 if (perm.modeFlags == 0) {
5021 it.remove();
5022 }
5023 }
5024 if (perms.size() == 0) {
5025 mGrantedUriPermissions.remove(
5026 mGrantedUriPermissions.keyAt(i));
5027 N--;
5028 i--;
5029 }
5030 }
5031 }
5032 }
5033
5034 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5035 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005036 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 synchronized(this) {
5038 final ProcessRecord r = getRecordForAppLocked(caller);
5039 if (r == null) {
5040 throw new SecurityException("Unable to find app for caller "
5041 + caller
5042 + " when revoking permission to uri " + uri);
5043 }
5044 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005045 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 return;
5047 }
5048
5049 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5050 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5051 if (modeFlags == 0) {
5052 return;
5053 }
5054
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005055 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056
5057 final String authority = uri.getAuthority();
5058 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005059 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 if (cpr != null) {
5061 pi = cpr.info;
5062 } else {
5063 try {
5064 pi = pm.resolveContentProvider(authority,
5065 PackageManager.GET_URI_PERMISSION_PATTERNS);
5066 } catch (RemoteException ex) {
5067 }
5068 }
5069 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005070 Slog.w(TAG, "No content provider found for permission revoke: "
5071 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 return;
5073 }
5074
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005075 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 }
5077 }
5078
Dianne Hackborn7e269642010-08-25 19:50:20 -07005079 @Override
5080 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005081 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005082 synchronized(this) {
5083 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5084 return owner.getExternalTokenLocked();
5085 }
5086 }
5087
5088 @Override
5089 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5090 Uri uri, int modeFlags) {
5091 synchronized(this) {
5092 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5093 if (owner == null) {
5094 throw new IllegalArgumentException("Unknown owner: " + token);
5095 }
5096 if (fromUid != Binder.getCallingUid()) {
5097 if (Binder.getCallingUid() != Process.myUid()) {
5098 // Only system code can grant URI permissions on behalf
5099 // of other users.
5100 throw new SecurityException("nice try");
5101 }
5102 }
5103 if (targetPkg == null) {
5104 throw new IllegalArgumentException("null target");
5105 }
5106 if (uri == null) {
5107 throw new IllegalArgumentException("null uri");
5108 }
5109
5110 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5111 }
5112 }
5113
5114 @Override
5115 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5116 synchronized(this) {
5117 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5118 if (owner == null) {
5119 throw new IllegalArgumentException("Unknown owner: " + token);
5120 }
5121
5122 if (uri == null) {
5123 owner.removeUriPermissionsLocked(mode);
5124 } else {
5125 owner.removeUriPermissionLocked(uri, mode);
5126 }
5127 }
5128 }
5129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5131 synchronized (this) {
5132 ProcessRecord app =
5133 who != null ? getRecordForAppLocked(who) : null;
5134 if (app == null) return;
5135
5136 Message msg = Message.obtain();
5137 msg.what = WAIT_FOR_DEBUGGER_MSG;
5138 msg.obj = app;
5139 msg.arg1 = waiting ? 1 : 0;
5140 mHandler.sendMessage(msg);
5141 }
5142 }
5143
5144 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005145 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5146 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005148 outInfo.threshold = homeAppMem;
5149 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5150 outInfo.hiddenAppThreshold = hiddenAppMem;
5151 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005152 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005153 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5154 ProcessList.VISIBLE_APP_ADJ);
5155 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5156 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005157 }
5158
5159 // =========================================================
5160 // TASK MANAGEMENT
5161 // =========================================================
5162
5163 public List getTasks(int maxNum, int flags,
5164 IThumbnailReceiver receiver) {
5165 ArrayList list = new ArrayList();
5166
5167 PendingThumbnailsRecord pending = null;
5168 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005169 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170
5171 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005172 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5174 + ", receiver=" + receiver);
5175
5176 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5177 != PackageManager.PERMISSION_GRANTED) {
5178 if (receiver != null) {
5179 // If the caller wants to wait for pending thumbnails,
5180 // it ain't gonna get them.
5181 try {
5182 receiver.finished();
5183 } catch (RemoteException ex) {
5184 }
5185 }
5186 String msg = "Permission Denial: getTasks() from pid="
5187 + Binder.getCallingPid()
5188 + ", uid=" + Binder.getCallingUid()
5189 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005190 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 throw new SecurityException(msg);
5192 }
5193
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005194 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005195 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005196 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005197 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 TaskRecord curTask = null;
5199 int numActivities = 0;
5200 int numRunning = 0;
5201 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005202 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005204 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205
5206 // Initialize state for next task if needed.
5207 if (top == null ||
5208 (top.state == ActivityState.INITIALIZING
5209 && top.task == r.task)) {
5210 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 curTask = r.task;
5212 numActivities = numRunning = 0;
5213 }
5214
5215 // Add 'r' into the current task.
5216 numActivities++;
5217 if (r.app != null && r.app.thread != null) {
5218 numRunning++;
5219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220
Joe Onorato8a9b2202010-02-26 18:56:32 -08005221 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 TAG, r.intent.getComponent().flattenToShortString()
5223 + ": task=" + r.task);
5224
5225 // If the next one is a different task, generate a new
5226 // TaskInfo entry for what we have.
5227 if (next == null || next.task != curTask) {
5228 ActivityManager.RunningTaskInfo ci
5229 = new ActivityManager.RunningTaskInfo();
5230 ci.id = curTask.taskId;
5231 ci.baseActivity = r.intent.getComponent();
5232 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005233 if (top.thumbHolder != null) {
5234 ci.description = top.thumbHolder.lastDescription;
5235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 ci.numActivities = numActivities;
5237 ci.numRunning = numRunning;
5238 //System.out.println(
5239 // "#" + maxNum + ": " + " descr=" + ci.description);
5240 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005241 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 TAG, "State=" + top.state + "Idle=" + top.idle
5243 + " app=" + top.app
5244 + " thr=" + (top.app != null ? top.app.thread : null));
5245 if (top.state == ActivityState.RESUMED
5246 || top.state == ActivityState.PAUSING) {
5247 if (top.idle && top.app != null
5248 && top.app.thread != null) {
5249 topRecord = top;
5250 topThumbnail = top.app.thread;
5251 } else {
5252 top.thumbnailNeeded = true;
5253 }
5254 }
5255 if (pending == null) {
5256 pending = new PendingThumbnailsRecord(receiver);
5257 }
5258 pending.pendingRecords.add(top);
5259 }
5260 list.add(ci);
5261 maxNum--;
5262 top = null;
5263 }
5264 }
5265
5266 if (pending != null) {
5267 mPendingThumbnails.add(pending);
5268 }
5269 }
5270
Joe Onorato8a9b2202010-02-26 18:56:32 -08005271 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272
5273 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005274 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005275 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005276 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005278 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005279 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 }
5281 }
5282
5283 if (pending == null && receiver != null) {
5284 // In this case all thumbnails were available and the client
5285 // is being asked to be told when the remaining ones come in...
5286 // which is unusually, since the top-most currently running
5287 // activity should never have a canned thumbnail! Oh well.
5288 try {
5289 receiver.finished();
5290 } catch (RemoteException ex) {
5291 }
5292 }
5293
5294 return list;
5295 }
5296
5297 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5298 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005299 final int callingUid = Binder.getCallingUid();
5300 // If it's the system uid asking, then use the current user id.
5301 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5302 // require the entire list.
5303 final int callingUserId = callingUid == Process.SYSTEM_UID
5304 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 synchronized (this) {
5306 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5307 "getRecentTasks()");
5308
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005309 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311 final int N = mRecentTasks.size();
5312 ArrayList<ActivityManager.RecentTaskInfo> res
5313 = new ArrayList<ActivityManager.RecentTaskInfo>(
5314 maxNum < N ? maxNum : N);
5315 for (int i=0; i<N && maxNum > 0; i++) {
5316 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005317 // Only add calling user's recent tasks
5318 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005319 // Return the entry if desired by the caller. We always return
5320 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005321 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005322 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5323 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005324
Dianne Hackborn905577f2011-09-07 18:31:28 -07005325 if (i == 0
5326 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 || (tr.intent == null)
5328 || ((tr.intent.getFlags()
5329 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5330 ActivityManager.RecentTaskInfo rti
5331 = new ActivityManager.RecentTaskInfo();
5332 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005333 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 rti.baseIntent = new Intent(
5335 tr.intent != null ? tr.intent : tr.affinityIntent);
5336 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005337 rti.description = tr.lastDescription;
5338
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005339 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5340 // Check whether this activity is currently available.
5341 try {
5342 if (rti.origActivity != null) {
5343 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5344 continue;
5345 }
5346 } else if (rti.baseIntent != null) {
5347 if (pm.queryIntentActivities(rti.baseIntent,
5348 null, 0) == null) {
5349 continue;
5350 }
5351 }
5352 } catch (RemoteException e) {
5353 // Will never happen.
5354 }
5355 }
5356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 res.add(rti);
5358 maxNum--;
5359 }
5360 }
5361 return res;
5362 }
5363 }
5364
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005365 private TaskRecord taskForIdLocked(int id) {
5366 final int N = mRecentTasks.size();
5367 for (int i=0; i<N; i++) {
5368 TaskRecord tr = mRecentTasks.get(i);
5369 if (tr.taskId == id) {
5370 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005371 }
5372 }
5373 return null;
5374 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005375
5376 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5377 synchronized (this) {
5378 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5379 "getTaskThumbnails()");
5380 TaskRecord tr = taskForIdLocked(id);
5381 if (tr != null) {
5382 return mMainStack.getTaskThumbnailsLocked(tr);
5383 }
5384 }
5385 return null;
5386 }
5387
5388 public boolean removeSubTask(int taskId, int subTaskIndex) {
5389 synchronized (this) {
5390 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5391 "removeSubTask()");
5392 long ident = Binder.clearCallingIdentity();
5393 try {
5394 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5395 } finally {
5396 Binder.restoreCallingIdentity(ident);
5397 }
5398 }
5399 }
5400
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005401 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005402 TaskRecord tr = root.task;
5403 Intent baseIntent = new Intent(
5404 tr.intent != null ? tr.intent : tr.affinityIntent);
5405 ComponentName component = baseIntent.getComponent();
5406 if (component == null) {
5407 Slog.w(TAG, "Now component for base intent of task: " + tr);
5408 return;
5409 }
5410
5411 // Find any running services associated with this app.
5412 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005413 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005414 if (sr.packageName.equals(component.getPackageName())) {
5415 services.add(sr);
5416 }
5417 }
5418
5419 // Take care of any running services associated with the app.
5420 for (int i=0; i<services.size(); i++) {
5421 ServiceRecord sr = services.get(i);
5422 if (sr.startRequested) {
5423 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005424 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005425 stopServiceLocked(sr);
5426 } else {
5427 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
5428 sr.makeNextStartId(), baseIntent, -1));
5429 if (sr.app != null && sr.app.thread != null) {
5430 sendServiceArgsLocked(sr, false);
5431 }
5432 }
5433 }
5434 }
5435
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005436 if (killProcesses) {
5437 // Find any running processes associated with this app.
5438 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5439 SparseArray<ProcessRecord> appProcs
5440 = mProcessNames.getMap().get(component.getPackageName());
5441 if (appProcs != null) {
5442 for (int i=0; i<appProcs.size(); i++) {
5443 procs.add(appProcs.valueAt(i));
5444 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005445 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005446
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005447 // Kill the running processes.
5448 for (int i=0; i<procs.size(); i++) {
5449 ProcessRecord pr = procs.get(i);
5450 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5451 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5452 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5453 pr.processName, pr.setAdj, "remove task");
5454 Process.killProcessQuiet(pr.pid);
5455 } else {
5456 pr.waitingToKill = "remove task";
5457 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005458 }
5459 }
5460 }
5461
5462 public boolean removeTask(int taskId, int flags) {
5463 synchronized (this) {
5464 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5465 "removeTask()");
5466 long ident = Binder.clearCallingIdentity();
5467 try {
5468 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5469 if (r != null) {
5470 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005471 cleanUpRemovedTaskLocked(r,
5472 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005473 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005474 } else {
5475 TaskRecord tr = null;
5476 int i=0;
5477 while (i < mRecentTasks.size()) {
5478 TaskRecord t = mRecentTasks.get(i);
5479 if (t.taskId == taskId) {
5480 tr = t;
5481 break;
5482 }
5483 i++;
5484 }
5485 if (tr != null) {
5486 if (tr.numActivities <= 0) {
5487 // Caller is just removing a recent task that is
5488 // not actively running. That is easy!
5489 mRecentTasks.remove(i);
5490 } else {
5491 Slog.w(TAG, "removeTask: task " + taskId
5492 + " does not have activities to remove, "
5493 + " but numActivities=" + tr.numActivities
5494 + ": " + tr);
5495 }
5496 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005497 }
5498 } finally {
5499 Binder.restoreCallingIdentity(ident);
5500 }
5501 }
5502 return false;
5503 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5506 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005507 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 TaskRecord jt = startTask;
5509
5510 // First look backwards
5511 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005512 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 if (r.task != jt) {
5514 jt = r.task;
5515 if (affinity.equals(jt.affinity)) {
5516 return j;
5517 }
5518 }
5519 }
5520
5521 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005522 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 jt = startTask;
5524 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005525 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 if (r.task != jt) {
5527 if (affinity.equals(jt.affinity)) {
5528 return j;
5529 }
5530 jt = r.task;
5531 }
5532 }
5533
5534 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005535 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 return N-1;
5537 }
5538
5539 return -1;
5540 }
5541
5542 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005543 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005545 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5547 "moveTaskToFront()");
5548
5549 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005550 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5551 Binder.getCallingUid(), "Task to front")) {
5552 return;
5553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 final long origId = Binder.clearCallingIdentity();
5555 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005556 TaskRecord tr = taskForIdLocked(task);
5557 if (tr != null) {
5558 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5559 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005561 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5562 // Caller wants the home activity moved with it. To accomplish this,
5563 // we'll just move the home task to the top first.
5564 mMainStack.moveHomeToFrontLocked();
5565 }
5566 mMainStack.moveTaskToFrontLocked(tr, null);
5567 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005569 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5570 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005572 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5573 mMainStack.mUserLeaving = true;
5574 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005575 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5576 // Caller wants the home activity moved with it. To accomplish this,
5577 // we'll just move the home task to the top first.
5578 mMainStack.moveHomeToFrontLocked();
5579 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005580 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 return;
5582 }
5583 }
5584 } finally {
5585 Binder.restoreCallingIdentity(origId);
5586 }
5587 }
5588 }
5589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 public void moveTaskToBack(int task) {
5591 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5592 "moveTaskToBack()");
5593
5594 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005595 if (mMainStack.mResumedActivity != null
5596 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005597 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5598 Binder.getCallingUid(), "Task to back")) {
5599 return;
5600 }
5601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005603 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 Binder.restoreCallingIdentity(origId);
5605 }
5606 }
5607
5608 /**
5609 * Moves an activity, and all of the other activities within the same task, to the bottom
5610 * of the history stack. The activity's order within the task is unchanged.
5611 *
5612 * @param token A reference to the activity we wish to move
5613 * @param nonRoot If false then this only works if the activity is the root
5614 * of a task; if true it will work for any activity in a task.
5615 * @return Returns true if the move completed, false if not.
5616 */
5617 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005618 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 synchronized(this) {
5620 final long origId = Binder.clearCallingIdentity();
5621 int taskId = getTaskForActivityLocked(token, !nonRoot);
5622 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005623 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 }
5625 Binder.restoreCallingIdentity(origId);
5626 }
5627 return false;
5628 }
5629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 public void moveTaskBackwards(int task) {
5631 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5632 "moveTaskBackwards()");
5633
5634 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005635 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5636 Binder.getCallingUid(), "Task backwards")) {
5637 return;
5638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 final long origId = Binder.clearCallingIdentity();
5640 moveTaskBackwardsLocked(task);
5641 Binder.restoreCallingIdentity(origId);
5642 }
5643 }
5644
5645 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005646 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 }
5648
5649 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5650 synchronized(this) {
5651 return getTaskForActivityLocked(token, onlyRoot);
5652 }
5653 }
5654
5655 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005656 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 TaskRecord lastTask = null;
5658 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005659 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005660 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 if (!onlyRoot || lastTask != r.task) {
5662 return r.task.taskId;
5663 }
5664 return -1;
5665 }
5666 lastTask = r.task;
5667 }
5668
5669 return -1;
5670 }
5671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 // =========================================================
5673 // THUMBNAILS
5674 // =========================================================
5675
5676 public void reportThumbnail(IBinder token,
5677 Bitmap thumbnail, CharSequence description) {
5678 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5679 final long origId = Binder.clearCallingIdentity();
5680 sendPendingThumbnail(null, token, thumbnail, description, true);
5681 Binder.restoreCallingIdentity(origId);
5682 }
5683
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005684 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 Bitmap thumbnail, CharSequence description, boolean always) {
5686 TaskRecord task = null;
5687 ArrayList receivers = null;
5688
5689 //System.out.println("Send pending thumbnail: " + r);
5690
5691 synchronized(this) {
5692 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005693 r = mMainStack.isInStackLocked(token);
5694 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 return;
5696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005698 if (thumbnail == null && r.thumbHolder != null) {
5699 thumbnail = r.thumbHolder.lastThumbnail;
5700 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 }
5702 if (thumbnail == null && !always) {
5703 // If there is no thumbnail, and this entry is not actually
5704 // going away, then abort for now and pick up the next
5705 // thumbnail we get.
5706 return;
5707 }
5708 task = r.task;
5709
5710 int N = mPendingThumbnails.size();
5711 int i=0;
5712 while (i<N) {
5713 PendingThumbnailsRecord pr =
5714 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5715 //System.out.println("Looking in " + pr.pendingRecords);
5716 if (pr.pendingRecords.remove(r)) {
5717 if (receivers == null) {
5718 receivers = new ArrayList();
5719 }
5720 receivers.add(pr);
5721 if (pr.pendingRecords.size() == 0) {
5722 pr.finished = true;
5723 mPendingThumbnails.remove(i);
5724 N--;
5725 continue;
5726 }
5727 }
5728 i++;
5729 }
5730 }
5731
5732 if (receivers != null) {
5733 final int N = receivers.size();
5734 for (int i=0; i<N; i++) {
5735 try {
5736 PendingThumbnailsRecord pr =
5737 (PendingThumbnailsRecord)receivers.get(i);
5738 pr.receiver.newThumbnail(
5739 task != null ? task.taskId : -1, thumbnail, description);
5740 if (pr.finished) {
5741 pr.receiver.finished();
5742 }
5743 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005744 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 }
5746 }
5747 }
5748 }
5749
5750 // =========================================================
5751 // CONTENT PROVIDERS
5752 // =========================================================
5753
Jeff Brown10e89712011-07-08 18:52:57 -07005754 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5755 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005757 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005758 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005759 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 } catch (RemoteException ex) {
5761 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005762 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005763 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5764 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 if (providers != null) {
5766 final int N = providers.size();
5767 for (int i=0; i<N; i++) {
5768 ProviderInfo cpi =
5769 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005770
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005771 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005772 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 if (cpr == null) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005774 cpr = new ContentProviderRecord(cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005775 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005777 if (DEBUG_MU)
5778 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 app.pubProviders.put(cpi.name, cpr);
5780 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005781 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 }
5783 }
5784 return providers;
5785 }
5786
5787 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005788 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005790 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005792 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005793 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 return null;
5795 }
5796 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005797 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 == PackageManager.PERMISSION_GRANTED) {
5799 return null;
5800 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005801
5802 PathPermission[] pps = cpi.pathPermissions;
5803 if (pps != null) {
5804 int i = pps.length;
5805 while (i > 0) {
5806 i--;
5807 PathPermission pp = pps[i];
5808 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005809 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005810 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005811 return null;
5812 }
5813 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005814 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005815 == PackageManager.PERMISSION_GRANTED) {
5816 return null;
5817 }
5818 }
5819 }
5820
Dianne Hackbornb424b632010-08-18 15:59:05 -07005821 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5822 if (perms != null) {
5823 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5824 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5825 return null;
5826 }
5827 }
5828 }
5829
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005830 String msg;
5831 if (!cpi.exported) {
5832 msg = "Permission Denial: opening provider " + cpi.name
5833 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5834 + ", uid=" + callingUid + ") that is not exported from uid "
5835 + cpi.applicationInfo.uid;
5836 } else {
5837 msg = "Permission Denial: opening provider " + cpi.name
5838 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5839 + ", uid=" + callingUid + ") requires "
5840 + cpi.readPermission + " or " + cpi.writePermission;
5841 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005842 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 return msg;
5844 }
5845
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005846 boolean incProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
5847 if (r != null) {
5848 Integer cnt = r.conProviders.get(cpr);
5849 if (DEBUG_PROVIDER) Slog.v(TAG,
5850 "Adding provider requested by "
5851 + r.processName + " from process "
5852 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5853 + " cnt=" + (cnt == null ? 1 : cnt));
5854 if (cnt == null) {
5855 cpr.clients.add(r);
5856 r.conProviders.put(cpr, new Integer(1));
5857 return true;
5858 } else {
5859 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5860 }
5861 } else {
5862 cpr.externals++;
5863 }
5864 return false;
5865 }
5866
5867 boolean decProviderCount(ProcessRecord r, ContentProviderRecord cpr) {
5868 if (r != null) {
5869 Integer cnt = r.conProviders.get(cpr);
5870 if (DEBUG_PROVIDER) Slog.v(TAG,
5871 "Removing provider requested by "
5872 + r.processName + " from process "
5873 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5874 + " cnt=" + cnt);
5875 if (cnt == null || cnt.intValue() <= 1) {
5876 cpr.clients.remove(r);
5877 r.conProviders.remove(cpr);
5878 return true;
5879 } else {
5880 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5881 }
5882 } else {
5883 cpr.externals++;
5884 }
5885 return false;
5886 }
5887
Amith Yamasani742a6712011-05-04 14:49:28 -07005888 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
5889 String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 ContentProviderRecord cpr;
5891 ProviderInfo cpi = null;
5892
5893 synchronized(this) {
5894 ProcessRecord r = null;
5895 if (caller != null) {
5896 r = getRecordForAppLocked(caller);
5897 if (r == null) {
5898 throw new SecurityException(
5899 "Unable to find app for caller " + caller
5900 + " (pid=" + Binder.getCallingPid()
5901 + ") when getting content provider " + name);
5902 }
5903 }
5904
5905 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005906 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005907 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005908 boolean providerRunning = cpr != null;
5909 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005911 String msg;
5912 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5913 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 }
5915
5916 if (r != null && cpr.canRunHere(r)) {
5917 // This provider has been published or is in the process
5918 // of being published... but it is also allowed to run
5919 // in the caller's process, so don't make a connection
5920 // and just let the caller instantiate its own instance.
5921 if (cpr.provider != null) {
5922 // don't give caller the provider object, it needs
5923 // to make its own.
5924 cpr = new ContentProviderRecord(cpr);
5925 }
5926 return cpr;
5927 }
5928
5929 final long origId = Binder.clearCallingIdentity();
5930
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005931 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 // return it right away.
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005933 final boolean countChanged = incProviderCount(r, cpr);
5934 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005935 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005936 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005937 // make sure to count it as being accessed and thus
5938 // back up on the LRU list. This is good because
5939 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005940 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07005941 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07005942 }
5943
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005944 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005945 if (false) {
5946 if (cpr.name.flattenToShortString().equals(
5947 "com.android.providers.calendar/.CalendarProvider2")) {
5948 Slog.v(TAG, "****************** KILLING "
5949 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005950 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005951 }
5952 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005953 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005954 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
5955 // NOTE: there is still a race here where a signal could be
5956 // pending on the process even though we managed to update its
5957 // adj level. Not sure what to do about this, but at least
5958 // the race is now smaller.
5959 if (!success) {
5960 // Uh oh... it looks like the provider's process
5961 // has been killed on us. We need to wait for a new
5962 // process to be started, and make sure its death
5963 // doesn't kill our process.
5964 Slog.i(TAG,
5965 "Existing provider " + cpr.name.flattenToShortString()
5966 + " is crashing; detaching " + r);
5967 boolean lastRef = decProviderCount(r, cpr);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005968 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005969 if (!lastRef) {
5970 // This wasn't the last ref our process had on
5971 // the provider... we have now been killed, bail.
5972 return null;
5973 }
5974 providerRunning = false;
5975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
5977
5978 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005981 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005983 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07005984 resolveContentProvider(name,
5985 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 } catch (RemoteException ex) {
5987 }
5988 if (cpi == null) {
5989 return null;
5990 }
5991
Amith Yamasani742a6712011-05-04 14:49:28 -07005992 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
5993 Binder.getOrigCallingUser());
5994
Dianne Hackbornb424b632010-08-18 15:59:05 -07005995 String msg;
5996 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5997 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 }
5999
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006000 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006001 && !cpi.processName.equals("system")) {
6002 // If this content provider does not run in the system
6003 // process, and the system is not yet ready to run other
6004 // processes, then fail fast instead of hanging.
6005 throw new IllegalArgumentException(
6006 "Attempt to launch content provider before system ready");
6007 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006008
6009 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006010 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 final boolean firstClass = cpr == null;
6012 if (firstClass) {
6013 try {
6014 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006015 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 getApplicationInfo(
6017 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006018 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006020 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 + cpi.name);
6022 return null;
6023 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006024 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006025 cpr = new ContentProviderRecord(cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 } catch (RemoteException ex) {
6027 // pm is in same process, this will never happen.
6028 }
6029 }
6030
6031 if (r != null && cpr.canRunHere(r)) {
6032 // If this is a multiprocess provider, then just return its
6033 // info and allow the caller to instantiate it. Only do
6034 // this if the provider is the same user as the caller's
6035 // process, or can run as root (so can be in any process).
6036 return cpr;
6037 }
6038
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006039 if (DEBUG_PROVIDER) {
6040 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006041 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006042 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 }
6044
6045 // This is single process, and our app is now connecting to it.
6046 // See if we are already in the process of launching this
6047 // provider.
6048 final int N = mLaunchingProviders.size();
6049 int i;
6050 for (i=0; i<N; i++) {
6051 if (mLaunchingProviders.get(i) == cpr) {
6052 break;
6053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 }
6055
6056 // If the provider is not already being launched, then get it
6057 // started.
6058 if (i >= N) {
6059 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006060
6061 try {
6062 // Content provider is now in use, its package can't be stopped.
6063 try {
6064 AppGlobals.getPackageManager().setPackageStoppedState(
6065 cpr.appInfo.packageName, false);
6066 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006067 } catch (IllegalArgumentException e) {
6068 Slog.w(TAG, "Failed trying to unstop package "
6069 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006070 }
6071
6072 ProcessRecord proc = startProcessLocked(cpi.processName,
6073 cpr.appInfo, false, 0, "content provider",
6074 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006075 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006076 if (proc == null) {
6077 Slog.w(TAG, "Unable to launch app "
6078 + cpi.applicationInfo.packageName + "/"
6079 + cpi.applicationInfo.uid + " for provider "
6080 + name + ": process is bad");
6081 return null;
6082 }
6083 cpr.launchingApp = proc;
6084 mLaunchingProviders.add(cpr);
6085 } finally {
6086 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
6089
6090 // Make sure the provider is published (the same provider class
6091 // may be published under multiple names).
6092 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006093 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006095 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006096 incProviderCount(r, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 }
6098 }
6099
6100 // Wait for the provider to be published...
6101 synchronized (cpr) {
6102 while (cpr.provider == null) {
6103 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006104 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 + cpi.applicationInfo.packageName + "/"
6106 + cpi.applicationInfo.uid + " for provider "
6107 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006108 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 cpi.applicationInfo.packageName,
6110 cpi.applicationInfo.uid, name);
6111 return null;
6112 }
6113 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006114 if (DEBUG_MU) {
6115 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6116 + cpr.launchingApp);
6117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 cpr.wait();
6119 } catch (InterruptedException ex) {
6120 }
6121 }
6122 }
6123 return cpr;
6124 }
6125
6126 public final ContentProviderHolder getContentProvider(
6127 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006128 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 if (caller == null) {
6130 String msg = "null IApplicationThread when getting content provider "
6131 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006132 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 throw new SecurityException(msg);
6134 }
6135
Amith Yamasani742a6712011-05-04 14:49:28 -07006136 ContentProviderHolder contentProvider = getContentProviderImpl(caller, name);
6137 return contentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 }
6139
6140 private ContentProviderHolder getContentProviderExternal(String name) {
6141 return getContentProviderImpl(null, name);
6142 }
6143
6144 /**
6145 * Drop a content provider from a ProcessRecord's bookkeeping
6146 * @param cpr
6147 */
6148 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006149 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006151 int userId = UserId.getUserId(Binder.getCallingUid());
6152 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006154 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006155 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006156 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 return;
6158 }
6159 final ProcessRecord r = getRecordForAppLocked(caller);
6160 if (r == null) {
6161 throw new SecurityException(
6162 "Unable to find app for caller " + caller +
6163 " when removing content provider " + name);
6164 }
6165 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006166 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006167 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6168 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6169 + r.info.processName + " from process "
6170 + localCpr.appInfo.processName);
6171 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006173 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006174 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 return;
6176 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006177 if (decProviderCount(r, localCpr)) {
6178 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 }
6182 }
6183
6184 private void removeContentProviderExternal(String name) {
6185 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006186 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6187 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 if(cpr == null) {
6189 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006190 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 return;
6192 }
6193
6194 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006195 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006196 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6197 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 localCpr.externals--;
6199 if (localCpr.externals < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006200 Slog.e(TAG, "Externals < 0 for content provider " + localCpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 }
6202 updateOomAdjLocked();
6203 }
6204 }
6205
6206 public final void publishContentProviders(IApplicationThread caller,
6207 List<ContentProviderHolder> providers) {
6208 if (providers == null) {
6209 return;
6210 }
6211
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006212 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 synchronized(this) {
6214 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006215 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006216 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 if (r == null) {
6218 throw new SecurityException(
6219 "Unable to find app for caller " + caller
6220 + " (pid=" + Binder.getCallingPid()
6221 + ") when publishing content providers");
6222 }
6223
6224 final long origId = Binder.clearCallingIdentity();
6225
6226 final int N = providers.size();
6227 for (int i=0; i<N; i++) {
6228 ContentProviderHolder src = providers.get(i);
6229 if (src == null || src.info == null || src.provider == null) {
6230 continue;
6231 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006232 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006233 if (DEBUG_MU)
6234 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006236 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006237 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 String names[] = dst.info.authority.split(";");
6239 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006240 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 }
6242
6243 int NL = mLaunchingProviders.size();
6244 int j;
6245 for (j=0; j<NL; j++) {
6246 if (mLaunchingProviders.get(j) == dst) {
6247 mLaunchingProviders.remove(j);
6248 j--;
6249 NL--;
6250 }
6251 }
6252 synchronized (dst) {
6253 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006254 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 dst.notifyAll();
6256 }
6257 updateOomAdjLocked(r);
6258 }
6259 }
6260
6261 Binder.restoreCallingIdentity(origId);
6262 }
6263 }
6264
6265 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006266 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006267 synchronized (mSelf) {
6268 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6269 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006270 if (providers != null) {
6271 for (int i=providers.size()-1; i>=0; i--) {
6272 ProviderInfo pi = (ProviderInfo)providers.get(i);
6273 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6274 Slog.w(TAG, "Not installing system proc provider " + pi.name
6275 + ": not system .apk");
6276 providers.remove(i);
6277 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006278 }
6279 }
6280 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006281 if (providers != null) {
6282 mSystemThread.installSystemProviders(providers);
6283 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006284
6285 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006286
6287 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
6289
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006290 /**
6291 * Allows app to retrieve the MIME type of a URI without having permission
6292 * to access its content provider.
6293 *
6294 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6295 *
6296 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6297 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6298 */
6299 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006300 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006301 final String name = uri.getAuthority();
6302 final long ident = Binder.clearCallingIdentity();
6303 ContentProviderHolder holder = null;
6304
6305 try {
6306 holder = getContentProviderExternal(name);
6307 if (holder != null) {
6308 return holder.provider.getType(uri);
6309 }
6310 } catch (RemoteException e) {
6311 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6312 return null;
6313 } finally {
6314 if (holder != null) {
6315 removeContentProviderExternal(name);
6316 }
6317 Binder.restoreCallingIdentity(ident);
6318 }
6319
6320 return null;
6321 }
6322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 // =========================================================
6324 // GLOBAL MANAGEMENT
6325 // =========================================================
6326
6327 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006328 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 String proc = customProcess != null ? customProcess : info.processName;
6330 BatteryStatsImpl.Uid.Proc ps = null;
6331 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006332 int uid = info.uid;
6333 if (isolated) {
6334 int userId = UserId.getUserId(uid);
6335 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6336 uid = 0;
6337 while (true) {
6338 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6339 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6340 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6341 }
6342 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6343 mNextIsolatedProcessUid++;
6344 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6345 // No process for this uid, use it.
6346 break;
6347 }
6348 stepsLeft--;
6349 if (stepsLeft <= 0) {
6350 return null;
6351 }
6352 }
6353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 synchronized (stats) {
6355 ps = stats.getProcessStatsLocked(info.uid, proc);
6356 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006357 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006360 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6361 ProcessRecord app;
6362 if (!isolated) {
6363 app = getProcessRecordLocked(info.processName, info.uid);
6364 } else {
6365 app = null;
6366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367
6368 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006369 app = newProcessRecordLocked(null, info, null, isolated);
6370 mProcessNames.put(info.processName, app.uid, app);
6371 if (isolated) {
6372 mIsolatedProcesses.put(app.uid, app);
6373 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006374 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 }
6376
Dianne Hackborne7f97212011-02-24 14:40:20 -08006377 // This package really, really can not be stopped.
6378 try {
6379 AppGlobals.getPackageManager().setPackageStoppedState(
6380 info.packageName, false);
6381 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006382 } catch (IllegalArgumentException e) {
6383 Slog.w(TAG, "Failed trying to unstop package "
6384 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006385 }
6386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6388 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6389 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006390 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 }
6392 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6393 mPersistentStartingProcesses.add(app);
6394 startProcessLocked(app, "added application", app.processName);
6395 }
6396
6397 return app;
6398 }
6399
6400 public void unhandledBack() {
6401 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6402 "unhandledBack()");
6403
6404 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006405 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006406 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 TAG, "Performing unhandledBack(): stack size = " + count);
6408 if (count > 1) {
6409 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006410 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6412 Binder.restoreCallingIdentity(origId);
6413 }
6414 }
6415 }
6416
6417 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006418 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 String name = uri.getAuthority();
6420 ContentProviderHolder cph = getContentProviderExternal(name);
6421 ParcelFileDescriptor pfd = null;
6422 if (cph != null) {
6423 // We record the binder invoker's uid in thread-local storage before
6424 // going to the content provider to open the file. Later, in the code
6425 // that handles all permissions checks, we look for this uid and use
6426 // that rather than the Activity Manager's own uid. The effect is that
6427 // we do the check against the caller's permissions even though it looks
6428 // to the content provider like the Activity Manager itself is making
6429 // the request.
6430 sCallerIdentity.set(new Identity(
6431 Binder.getCallingPid(), Binder.getCallingUid()));
6432 try {
6433 pfd = cph.provider.openFile(uri, "r");
6434 } catch (FileNotFoundException e) {
6435 // do nothing; pfd will be returned null
6436 } finally {
6437 // Ensure that whatever happens, we clean up the identity state
6438 sCallerIdentity.remove();
6439 }
6440
6441 // We've got the fd now, so we're done with the provider.
6442 removeContentProviderExternal(name);
6443 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006444 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 }
6446 return pfd;
6447 }
6448
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006449 // Actually is sleeping or shutting down or whatever else in the future
6450 // is an inactive state.
6451 public boolean isSleeping() {
6452 return mSleeping || mShuttingDown;
6453 }
6454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 public void goingToSleep() {
6456 synchronized(this) {
6457 mSleeping = true;
6458 mWindowManager.setEventDispatching(false);
6459
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006460 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006461
6462 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006463 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006464 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6465 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006466 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 }
6468 }
6469
Dianne Hackborn55280a92009-05-07 15:53:46 -07006470 public boolean shutdown(int timeout) {
6471 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6472 != PackageManager.PERMISSION_GRANTED) {
6473 throw new SecurityException("Requires permission "
6474 + android.Manifest.permission.SHUTDOWN);
6475 }
6476
6477 boolean timedout = false;
6478
6479 synchronized(this) {
6480 mShuttingDown = true;
6481 mWindowManager.setEventDispatching(false);
6482
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006483 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006484 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006485 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006486 while (mMainStack.mResumedActivity != null
Dianne Hackborncbb722e2012-02-07 18:33:49 -08006487 || mMainStack.mPausingActivities.size() > 0) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006488 long delay = endTime - System.currentTimeMillis();
6489 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006490 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006491 timedout = true;
6492 break;
6493 }
6494 try {
6495 this.wait();
6496 } catch (InterruptedException e) {
6497 }
6498 }
6499 }
6500 }
6501
6502 mUsageStatsService.shutdown();
6503 mBatteryStatsService.shutdown();
6504
6505 return timedout;
6506 }
6507
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006508 public final void activitySlept(IBinder token) {
6509 if (localLOGV) Slog.v(
6510 TAG, "Activity slept: token=" + token);
6511
6512 ActivityRecord r = null;
6513
6514 final long origId = Binder.clearCallingIdentity();
6515
6516 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006517 r = mMainStack.isInStackLocked(token);
6518 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006519 mMainStack.activitySleptLocked(r);
6520 }
6521 }
6522
6523 Binder.restoreCallingIdentity(origId);
6524 }
6525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 public void wakingUp() {
6527 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 mWindowManager.setEventDispatching(true);
6529 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006530 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006531 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
6533 }
6534
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006535 public void stopAppSwitches() {
6536 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6537 != PackageManager.PERMISSION_GRANTED) {
6538 throw new SecurityException("Requires permission "
6539 + android.Manifest.permission.STOP_APP_SWITCHES);
6540 }
6541
6542 synchronized(this) {
6543 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6544 + APP_SWITCH_DELAY_TIME;
6545 mDidAppSwitch = false;
6546 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6547 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6548 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6549 }
6550 }
6551
6552 public void resumeAppSwitches() {
6553 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6554 != PackageManager.PERMISSION_GRANTED) {
6555 throw new SecurityException("Requires permission "
6556 + android.Manifest.permission.STOP_APP_SWITCHES);
6557 }
6558
6559 synchronized(this) {
6560 // Note that we don't execute any pending app switches... we will
6561 // let those wait until either the timeout, or the next start
6562 // activity request.
6563 mAppSwitchesAllowedTime = 0;
6564 }
6565 }
6566
6567 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6568 String name) {
6569 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6570 return true;
6571 }
6572
6573 final int perm = checkComponentPermission(
6574 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006575 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006576 if (perm == PackageManager.PERMISSION_GRANTED) {
6577 return true;
6578 }
6579
Joe Onorato8a9b2202010-02-26 18:56:32 -08006580 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006581 return false;
6582 }
6583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 public void setDebugApp(String packageName, boolean waitForDebugger,
6585 boolean persistent) {
6586 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6587 "setDebugApp()");
6588
6589 // Note that this is not really thread safe if there are multiple
6590 // callers into it at the same time, but that's not a situation we
6591 // care about.
6592 if (persistent) {
6593 final ContentResolver resolver = mContext.getContentResolver();
6594 Settings.System.putString(
6595 resolver, Settings.System.DEBUG_APP,
6596 packageName);
6597 Settings.System.putInt(
6598 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6599 waitForDebugger ? 1 : 0);
6600 }
6601
6602 synchronized (this) {
6603 if (!persistent) {
6604 mOrigDebugApp = mDebugApp;
6605 mOrigWaitForDebugger = mWaitForDebugger;
6606 }
6607 mDebugApp = packageName;
6608 mWaitForDebugger = waitForDebugger;
6609 mDebugTransient = !persistent;
6610 if (packageName != null) {
6611 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006612 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 Binder.restoreCallingIdentity(origId);
6614 }
6615 }
6616 }
6617
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006618 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6619 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6620 synchronized (this) {
6621 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6622 if (!isDebuggable) {
6623 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6624 throw new SecurityException("Process not debuggable: " + app.packageName);
6625 }
6626 }
6627 mProfileApp = processName;
6628 mProfileFile = profileFile;
6629 if (mProfileFd != null) {
6630 try {
6631 mProfileFd.close();
6632 } catch (IOException e) {
6633 }
6634 mProfileFd = null;
6635 }
6636 mProfileFd = profileFd;
6637 mProfileType = 0;
6638 mAutoStopProfiler = autoStopProfiler;
6639 }
6640 }
6641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 public void setAlwaysFinish(boolean enabled) {
6643 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6644 "setAlwaysFinish()");
6645
6646 Settings.System.putInt(
6647 mContext.getContentResolver(),
6648 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6649
6650 synchronized (this) {
6651 mAlwaysFinishActivities = enabled;
6652 }
6653 }
6654
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006655 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006657 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006659 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 }
6661 }
6662
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006663 public boolean isUserAMonkey() {
6664 // For now the fact that there is a controller implies
6665 // we have a monkey.
6666 synchronized (this) {
6667 return mController != null;
6668 }
6669 }
6670
Jeff Sharkeya4620792011-05-20 15:29:23 -07006671 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006672 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6673 "registerProcessObserver()");
6674 synchronized (this) {
6675 mProcessObservers.register(observer);
6676 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006677 }
6678
6679 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006680 synchronized (this) {
6681 mProcessObservers.unregister(observer);
6682 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006683 }
6684
Daniel Sandler69a48172010-06-23 16:29:36 -04006685 public void setImmersive(IBinder token, boolean immersive) {
6686 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006687 ActivityRecord r = mMainStack.isInStackLocked(token);
6688 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006689 throw new IllegalArgumentException();
6690 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006691 r.immersive = immersive;
6692 }
6693 }
6694
6695 public boolean isImmersive(IBinder token) {
6696 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006697 ActivityRecord r = mMainStack.isInStackLocked(token);
6698 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006699 throw new IllegalArgumentException();
6700 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006701 return r.immersive;
6702 }
6703 }
6704
6705 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006706 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006707 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006708 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006709 return (r != null) ? r.immersive : false;
6710 }
6711 }
6712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 public final void enterSafeMode() {
6714 synchronized(this) {
6715 // It only makes sense to do this before the system is ready
6716 // and started launching other packages.
6717 if (!mSystemReady) {
6718 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006719 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 } catch (RemoteException e) {
6721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 }
6723 }
6724 }
6725
Jeff Brownb09abc12011-01-13 21:08:27 -08006726 public final void showSafeModeOverlay() {
6727 View v = LayoutInflater.from(mContext).inflate(
6728 com.android.internal.R.layout.safe_mode, null);
6729 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6730 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6731 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6732 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6733 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6734 lp.format = v.getBackground().getOpacity();
6735 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6736 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6737 ((WindowManager)mContext.getSystemService(
6738 Context.WINDOW_SERVICE)).addView(v, lp);
6739 }
6740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 public void noteWakeupAlarm(IIntentSender sender) {
6742 if (!(sender instanceof PendingIntentRecord)) {
6743 return;
6744 }
6745 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6746 synchronized (stats) {
6747 if (mBatteryStatsService.isOnBattery()) {
6748 mBatteryStatsService.enforceCallingPermission();
6749 PendingIntentRecord rec = (PendingIntentRecord)sender;
6750 int MY_UID = Binder.getCallingUid();
6751 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6752 BatteryStatsImpl.Uid.Pkg pkg =
6753 stats.getPackageStatsLocked(uid, rec.key.packageName);
6754 pkg.incWakeupsLocked();
6755 }
6756 }
6757 }
6758
Dianne Hackborn64825172011-03-02 21:32:58 -08006759 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006761 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006763 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 // XXX Note: don't acquire main activity lock here, because the window
6765 // manager calls in with its locks held.
6766
6767 boolean killed = false;
6768 synchronized (mPidsSelfLocked) {
6769 int[] types = new int[pids.length];
6770 int worstType = 0;
6771 for (int i=0; i<pids.length; i++) {
6772 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6773 if (proc != null) {
6774 int type = proc.setAdj;
6775 types[i] = type;
6776 if (type > worstType) {
6777 worstType = type;
6778 }
6779 }
6780 }
6781
Dianne Hackborn64825172011-03-02 21:32:58 -08006782 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006784 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6785 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006786 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006788
6789 // If this is not a secure call, don't let it kill processes that
6790 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006791 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6792 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006793 }
6794
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006795 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 for (int i=0; i<pids.length; i++) {
6797 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6798 if (proc == null) {
6799 continue;
6800 }
6801 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006802 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006803 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006804 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6805 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006807 proc.killedBackground = true;
6808 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 }
6810 }
6811 }
6812 return killed;
6813 }
6814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 public final void startRunning(String pkg, String cls, String action,
6816 String data) {
6817 synchronized(this) {
6818 if (mStartRunning) {
6819 return;
6820 }
6821 mStartRunning = true;
6822 mTopComponent = pkg != null && cls != null
6823 ? new ComponentName(pkg, cls) : null;
6824 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6825 mTopData = data;
6826 if (!mSystemReady) {
6827 return;
6828 }
6829 }
6830
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006831 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 }
6833
6834 private void retrieveSettings() {
6835 final ContentResolver resolver = mContext.getContentResolver();
6836 String debugApp = Settings.System.getString(
6837 resolver, Settings.System.DEBUG_APP);
6838 boolean waitForDebugger = Settings.System.getInt(
6839 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6840 boolean alwaysFinishActivities = Settings.System.getInt(
6841 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6842
6843 Configuration configuration = new Configuration();
6844 Settings.System.getConfiguration(resolver, configuration);
6845
6846 synchronized (this) {
6847 mDebugApp = mOrigDebugApp = debugApp;
6848 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6849 mAlwaysFinishActivities = alwaysFinishActivities;
6850 // This happens before any activities are started, so we can
6851 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006852 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006853 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 }
6855 }
6856
6857 public boolean testIsSystemReady() {
6858 // no need to synchronize(this) just to read & return the value
6859 return mSystemReady;
6860 }
6861
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006862 private static File getCalledPreBootReceiversFile() {
6863 File dataDir = Environment.getDataDirectory();
6864 File systemDir = new File(dataDir, "system");
6865 File fname = new File(systemDir, "called_pre_boots.dat");
6866 return fname;
6867 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006868
6869 static final int LAST_DONE_VERSION = 10000;
6870
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006871 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6872 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6873 File file = getCalledPreBootReceiversFile();
6874 FileInputStream fis = null;
6875 try {
6876 fis = new FileInputStream(file);
6877 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006878 int fvers = dis.readInt();
6879 if (fvers == LAST_DONE_VERSION) {
6880 String vers = dis.readUTF();
6881 String codename = dis.readUTF();
6882 String build = dis.readUTF();
6883 if (android.os.Build.VERSION.RELEASE.equals(vers)
6884 && android.os.Build.VERSION.CODENAME.equals(codename)
6885 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6886 int num = dis.readInt();
6887 while (num > 0) {
6888 num--;
6889 String pkg = dis.readUTF();
6890 String cls = dis.readUTF();
6891 lastDoneReceivers.add(new ComponentName(pkg, cls));
6892 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006893 }
6894 }
6895 } catch (FileNotFoundException e) {
6896 } catch (IOException e) {
6897 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6898 } finally {
6899 if (fis != null) {
6900 try {
6901 fis.close();
6902 } catch (IOException e) {
6903 }
6904 }
6905 }
6906 return lastDoneReceivers;
6907 }
6908
6909 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6910 File file = getCalledPreBootReceiversFile();
6911 FileOutputStream fos = null;
6912 DataOutputStream dos = null;
6913 try {
6914 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6915 fos = new FileOutputStream(file);
6916 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006917 dos.writeInt(LAST_DONE_VERSION);
6918 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006919 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006920 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006921 dos.writeInt(list.size());
6922 for (int i=0; i<list.size(); i++) {
6923 dos.writeUTF(list.get(i).getPackageName());
6924 dos.writeUTF(list.get(i).getClassName());
6925 }
6926 } catch (IOException e) {
6927 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
6928 file.delete();
6929 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006930 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006931 if (dos != null) {
6932 try {
6933 dos.close();
6934 } catch (IOException e) {
6935 // TODO Auto-generated catch block
6936 e.printStackTrace();
6937 }
6938 }
6939 }
6940 }
6941
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006942 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 synchronized(this) {
6944 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006945 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 return;
6947 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006948
6949 // Check to see if there are any update receivers to run.
6950 if (!mDidUpdate) {
6951 if (mWaitingUpdate) {
6952 return;
6953 }
6954 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6955 List<ResolveInfo> ris = null;
6956 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006957 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006958 intent, null, 0);
6959 } catch (RemoteException e) {
6960 }
6961 if (ris != null) {
6962 for (int i=ris.size()-1; i>=0; i--) {
6963 if ((ris.get(i).activityInfo.applicationInfo.flags
6964 &ApplicationInfo.FLAG_SYSTEM) == 0) {
6965 ris.remove(i);
6966 }
6967 }
6968 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006969
6970 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
6971
6972 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006973 for (int i=0; i<ris.size(); i++) {
6974 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006975 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6976 if (lastDoneReceivers.contains(comp)) {
6977 ris.remove(i);
6978 i--;
6979 }
6980 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07006981
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006982 for (int i=0; i<ris.size(); i++) {
6983 ActivityInfo ai = ris.get(i).activityInfo;
6984 ComponentName comp = new ComponentName(ai.packageName, ai.name);
6985 doneReceivers.add(comp);
6986 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006987 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08006988 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07006989 finisher = new IIntentReceiver.Stub() {
6990 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07006991 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006992 boolean sticky) {
6993 // The raw IIntentReceiver interface is called
6994 // with the AM lock held, so redispatch to
6995 // execute our code without the lock.
6996 mHandler.post(new Runnable() {
6997 public void run() {
6998 synchronized (ActivityManagerService.this) {
6999 mDidUpdate = true;
7000 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007001 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007002 showBootMessage(mContext.getText(
7003 R.string.android_upgrading_complete),
7004 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007005 systemReady(goingCallback);
7006 }
7007 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007008 }
7009 };
7010 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007011 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007012 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007013 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007014 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7015 Process.SYSTEM_UID);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007016 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007017 mWaitingUpdate = true;
7018 }
7019 }
7020 }
7021 if (mWaitingUpdate) {
7022 return;
7023 }
7024 mDidUpdate = true;
7025 }
7026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 mSystemReady = true;
7028 if (!mStartRunning) {
7029 return;
7030 }
7031 }
7032
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007033 ArrayList<ProcessRecord> procsToKill = null;
7034 synchronized(mPidsSelfLocked) {
7035 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7036 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7037 if (!isAllowedWhileBooting(proc.info)){
7038 if (procsToKill == null) {
7039 procsToKill = new ArrayList<ProcessRecord>();
7040 }
7041 procsToKill.add(proc);
7042 }
7043 }
7044 }
7045
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007046 synchronized(this) {
7047 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007048 for (int i=procsToKill.size()-1; i>=0; i--) {
7049 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007050 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007051 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007052 }
7053 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007054
7055 // Now that we have cleaned up any update processes, we
7056 // are ready to start launching real processes and know that
7057 // we won't trample on them any more.
7058 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007059 }
7060
Joe Onorato8a9b2202010-02-26 18:56:32 -08007061 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007062 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 SystemClock.uptimeMillis());
7064
7065 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007066 // Make sure we have no pre-ready processes sitting around.
7067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7069 ResolveInfo ri = mContext.getPackageManager()
7070 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007071 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 CharSequence errorMsg = null;
7073 if (ri != null) {
7074 ActivityInfo ai = ri.activityInfo;
7075 ApplicationInfo app = ai.applicationInfo;
7076 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7077 mTopAction = Intent.ACTION_FACTORY_TEST;
7078 mTopData = null;
7079 mTopComponent = new ComponentName(app.packageName,
7080 ai.name);
7081 } else {
7082 errorMsg = mContext.getResources().getText(
7083 com.android.internal.R.string.factorytest_not_system);
7084 }
7085 } else {
7086 errorMsg = mContext.getResources().getText(
7087 com.android.internal.R.string.factorytest_no_action);
7088 }
7089 if (errorMsg != null) {
7090 mTopAction = null;
7091 mTopData = null;
7092 mTopComponent = null;
7093 Message msg = Message.obtain();
7094 msg.what = SHOW_FACTORY_ERROR_MSG;
7095 msg.getData().putCharSequence("msg", errorMsg);
7096 mHandler.sendMessage(msg);
7097 }
7098 }
7099 }
7100
7101 retrieveSettings();
7102
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007103 if (goingCallback != null) goingCallback.run();
7104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 synchronized (this) {
7106 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7107 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007108 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007109 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 if (apps != null) {
7111 int N = apps.size();
7112 int i;
7113 for (i=0; i<N; i++) {
7114 ApplicationInfo info
7115 = (ApplicationInfo)apps.get(i);
7116 if (info != null &&
7117 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007118 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 }
7120 }
7121 }
7122 } catch (RemoteException ex) {
7123 // pm is in same process, this will never happen.
7124 }
7125 }
7126
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007127 // Start up initial activity.
7128 mBooting = true;
7129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007131 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 Message msg = Message.obtain();
7133 msg.what = SHOW_UID_ERROR_MSG;
7134 mHandler.sendMessage(msg);
7135 }
7136 } catch (RemoteException e) {
7137 }
7138
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007139 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 }
7141 }
7142
Dan Egnorb7f03672009-12-09 16:22:32 -08007143 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007144 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007146 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007147 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 startAppProblemLocked(app);
7149 app.stopFreezingAllLocked();
7150 return handleAppCrashLocked(app);
7151 }
7152
Dan Egnorb7f03672009-12-09 16:22:32 -08007153 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007154 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007156 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007157 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7158 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 startAppProblemLocked(app);
7160 app.stopFreezingAllLocked();
7161 }
7162
7163 /**
7164 * Generate a process error record, suitable for attachment to a ProcessRecord.
7165 *
7166 * @param app The ProcessRecord in which the error occurred.
7167 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7168 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007169 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 * @param shortMsg Short message describing the crash.
7171 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007172 * @param stackTrace Full crash stack trace, may be null.
7173 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 * @return Returns a fully-formed AppErrorStateInfo record.
7175 */
7176 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007177 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 report.condition = condition;
7181 report.processName = app.processName;
7182 report.pid = app.pid;
7183 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007184 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 report.shortMsg = shortMsg;
7186 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007187 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188
7189 return report;
7190 }
7191
Dan Egnor42471dd2010-01-07 17:25:22 -08007192 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007193 synchronized (this) {
7194 app.crashing = false;
7195 app.crashingReport = null;
7196 app.notResponding = false;
7197 app.notRespondingReport = null;
7198 if (app.anrDialog == fromDialog) {
7199 app.anrDialog = null;
7200 }
7201 if (app.waitDialog == fromDialog) {
7202 app.waitDialog = null;
7203 }
7204 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007205 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007206 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007207 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7208 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007209 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 }
7212 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007213
Dan Egnorb7f03672009-12-09 16:22:32 -08007214 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 long now = SystemClock.uptimeMillis();
7216
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007217 Long crashTime;
7218 if (!app.isolated) {
7219 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7220 } else {
7221 crashTime = null;
7222 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007223 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007225 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007227 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007228 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007229 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7230 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007231 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007232 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007234 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 }
7236 }
7237 if (!app.persistent) {
7238 // We don't want to start this process again until the user
7239 // explicitly does so... but for persistent process, we really
7240 // need to keep it running. If a persistent process is actually
7241 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007242 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007243 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007244 if (!app.isolated) {
7245 // XXX We don't have a way to mark isolated processes
7246 // as bad, since they don't have a peristent identity.
7247 mBadProcesses.put(app.info.processName, app.uid, now);
7248 mProcessCrashTimes.remove(app.info.processName, app.uid);
7249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007251 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007252 // Don't let services in this process be restarted and potentially
7253 // annoy the user repeatedly. Unless it is persistent, since those
7254 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007255 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007256 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257 return false;
7258 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007259 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007260 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007261 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007262 if (r.app == app) {
7263 // If the top running activity is from this crashing
7264 // process, then terminate it to avoid getting in a loop.
7265 Slog.w(TAG, " Force finishing activity "
7266 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007267 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007268 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007269 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007270 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007271 // stopped, to avoid a situation where one will get
7272 // re-start our crashing activity once it gets resumed again.
7273 index--;
7274 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007275 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007276 if (r.state == ActivityState.RESUMED
7277 || r.state == ActivityState.PAUSING
7278 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007279 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007280 Slog.w(TAG, " Force finishing activity "
7281 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007282 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007283 Activity.RESULT_CANCELED, null, "crashed");
7284 }
7285 }
7286 }
7287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 }
7289
7290 // Bump up the crash count of any services currently running in the proc.
7291 if (app.services.size() != 0) {
7292 // Any services running in the application need to be placed
7293 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007294 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007296 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 sr.crashCount++;
7298 }
7299 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007300
7301 // If the crashing process is what we consider to be the "home process" and it has been
7302 // replaced by a third-party app, clear the package preferred activities from packages
7303 // with a home activity running in the process to prevent a repeatedly crashing app
7304 // from blocking the user to manually clear the list.
7305 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7306 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7307 Iterator it = mHomeProcess.activities.iterator();
7308 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007309 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007310 if (r.isHomeActivity) {
7311 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7312 try {
7313 ActivityThread.getPackageManager()
7314 .clearPackagePreferredActivities(r.packageName);
7315 } catch (RemoteException c) {
7316 // pm is in same process, this will never happen.
7317 }
7318 }
7319 }
7320 }
7321
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007322 if (!app.isolated) {
7323 // XXX Can't keep track of crash times for isolated processes,
7324 // because they don't have a perisistent identity.
7325 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7326 }
7327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007328 return true;
7329 }
7330
7331 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007332 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7333 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 skipCurrentReceiverLocked(app);
7335 }
7336
7337 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007338 for (BroadcastQueue queue : mBroadcastQueues) {
7339 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 }
7341 }
7342
Dan Egnor60d87622009-12-16 16:32:58 -08007343 /**
7344 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7345 * The application process will exit immediately after this call returns.
7346 * @param app object of the crashing app, null for the system server
7347 * @param crashInfo describing the exception
7348 */
7349 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007350 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007351 final String processName = app == null ? "system_server"
7352 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007353
7354 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007355 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007356 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007357 crashInfo.exceptionClassName,
7358 crashInfo.exceptionMessage,
7359 crashInfo.throwFileName,
7360 crashInfo.throwLineNumber);
7361
Jeff Sharkeya353d262011-10-28 11:12:06 -07007362 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007363
7364 crashApplication(r, crashInfo);
7365 }
7366
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007367 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007368 IBinder app,
7369 int violationMask,
7370 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007371 ProcessRecord r = findAppProcess(app, "StrictMode");
7372 if (r == null) {
7373 return;
7374 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007375
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007376 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007377 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007378 boolean logIt = true;
7379 synchronized (mAlreadyLoggedViolatedStacks) {
7380 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7381 logIt = false;
7382 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007383 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007384 // the relative pain numbers, without logging all
7385 // the stack traces repeatedly. We'd want to do
7386 // likewise in the client code, which also does
7387 // dup suppression, before the Binder call.
7388 } else {
7389 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7390 mAlreadyLoggedViolatedStacks.clear();
7391 }
7392 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7393 }
7394 }
7395 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007396 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007397 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007398 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007399
7400 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7401 AppErrorResult result = new AppErrorResult();
7402 synchronized (this) {
7403 final long origId = Binder.clearCallingIdentity();
7404
7405 Message msg = Message.obtain();
7406 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7407 HashMap<String, Object> data = new HashMap<String, Object>();
7408 data.put("result", result);
7409 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007410 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007411 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007412 msg.obj = data;
7413 mHandler.sendMessage(msg);
7414
7415 Binder.restoreCallingIdentity(origId);
7416 }
7417 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007418 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007419 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007420 }
7421
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007422 // Depending on the policy in effect, there could be a bunch of
7423 // these in quick succession so we try to batch these together to
7424 // minimize disk writes, number of dropbox entries, and maximize
7425 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007426 private void logStrictModeViolationToDropBox(
7427 ProcessRecord process,
7428 StrictMode.ViolationInfo info) {
7429 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007430 return;
7431 }
7432 final boolean isSystemApp = process == null ||
7433 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7434 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007435 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007436 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7437 final DropBoxManager dbox = (DropBoxManager)
7438 mContext.getSystemService(Context.DROPBOX_SERVICE);
7439
7440 // Exit early if the dropbox isn't configured to accept this report type.
7441 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7442
7443 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007444 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007445 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7446 synchronized (sb) {
7447 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007448 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007449 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7450 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007451 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7452 if (info.violationNumThisLoop != 0) {
7453 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7454 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007455 if (info.numAnimationsRunning != 0) {
7456 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7457 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007458 if (info.broadcastIntentAction != null) {
7459 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7460 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007461 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007462 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007463 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007464 if (info.numInstances != -1) {
7465 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7466 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007467 if (info.tags != null) {
7468 for (String tag : info.tags) {
7469 sb.append("Span-Tag: ").append(tag).append("\n");
7470 }
7471 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007472 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007473 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7474 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007475 }
7476 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007477
7478 // Only buffer up to ~64k. Various logging bits truncate
7479 // things at 128k.
7480 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007481 }
7482
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007483 // Flush immediately if the buffer's grown too large, or this
7484 // is a non-system app. Non-system apps are isolated with a
7485 // different tag & policy and not batched.
7486 //
7487 // Batching is useful during internal testing with
7488 // StrictMode settings turned up high. Without batching,
7489 // thousands of separate files could be created on boot.
7490 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007491 new Thread("Error dump: " + dropboxTag) {
7492 @Override
7493 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007494 String report;
7495 synchronized (sb) {
7496 report = sb.toString();
7497 sb.delete(0, sb.length());
7498 sb.trimToSize();
7499 }
7500 if (report.length() != 0) {
7501 dbox.addText(dropboxTag, report);
7502 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007503 }
7504 }.start();
7505 return;
7506 }
7507
7508 // System app batching:
7509 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007510 // An existing dropbox-writing thread is outstanding, so
7511 // we don't need to start it up. The existing thread will
7512 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007513 return;
7514 }
7515
7516 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7517 // (After this point, we shouldn't access AMS internal data structures.)
7518 new Thread("Error dump: " + dropboxTag) {
7519 @Override
7520 public void run() {
7521 // 5 second sleep to let stacks arrive and be batched together
7522 try {
7523 Thread.sleep(5000); // 5 seconds
7524 } catch (InterruptedException e) {}
7525
7526 String errorReport;
7527 synchronized (mStrictModeBuffer) {
7528 errorReport = mStrictModeBuffer.toString();
7529 if (errorReport.length() == 0) {
7530 return;
7531 }
7532 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7533 mStrictModeBuffer.trimToSize();
7534 }
7535 dbox.addText(dropboxTag, errorReport);
7536 }
7537 }.start();
7538 }
7539
Dan Egnor60d87622009-12-16 16:32:58 -08007540 /**
7541 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7542 * @param app object of the crashing app, null for the system server
7543 * @param tag reported by the caller
7544 * @param crashInfo describing the context of the error
7545 * @return true if the process should exit immediately (WTF is fatal)
7546 */
7547 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007548 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007549 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007550 final String processName = app == null ? "system_server"
7551 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007552
7553 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007554 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007555 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007556 tag, crashInfo.exceptionMessage);
7557
Jeff Sharkeya353d262011-10-28 11:12:06 -07007558 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007559
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007560 if (r != null && r.pid != Process.myPid() &&
7561 Settings.Secure.getInt(mContext.getContentResolver(),
7562 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007563 crashApplication(r, crashInfo);
7564 return true;
7565 } else {
7566 return false;
7567 }
7568 }
7569
7570 /**
7571 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7572 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7573 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007574 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007575 if (app == null) {
7576 return null;
7577 }
7578
7579 synchronized (this) {
7580 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7581 final int NA = apps.size();
7582 for (int ia=0; ia<NA; ia++) {
7583 ProcessRecord p = apps.valueAt(ia);
7584 if (p.thread != null && p.thread.asBinder() == app) {
7585 return p;
7586 }
7587 }
7588 }
7589
Dianne Hackborncb44d962011-03-10 17:02:27 -08007590 Slog.w(TAG, "Can't find mystery application for " + reason
7591 + " from pid=" + Binder.getCallingPid()
7592 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007593 return null;
7594 }
7595 }
7596
7597 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007598 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7599 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007600 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007601 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7602 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007603 // Watchdog thread ends up invoking this function (with
7604 // a null ProcessRecord) to add the stack file to dropbox.
7605 // Do not acquire a lock on this (am) in such cases, as it
7606 // could cause a potential deadlock, if and when watchdog
7607 // is invoked due to unavailability of lock on am and it
7608 // would prevent watchdog from killing system_server.
7609 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007610 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007611 return;
7612 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007613 // Note: ProcessRecord 'process' is guarded by the service
7614 // instance. (notably process.pkgList, which could otherwise change
7615 // concurrently during execution of this method)
7616 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007617 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007618 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007619 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007620 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7621 for (String pkg : process.pkgList) {
7622 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007623 try {
Dan Egnora455d192010-03-12 08:52:28 -08007624 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7625 if (pi != null) {
7626 sb.append(" v").append(pi.versionCode);
7627 if (pi.versionName != null) {
7628 sb.append(" (").append(pi.versionName).append(")");
7629 }
7630 }
7631 } catch (RemoteException e) {
7632 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007633 }
Dan Egnora455d192010-03-12 08:52:28 -08007634 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007635 }
Dan Egnora455d192010-03-12 08:52:28 -08007636 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007637 }
7638
7639 private static String processClass(ProcessRecord process) {
7640 if (process == null || process.pid == MY_PID) {
7641 return "system_server";
7642 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7643 return "system_app";
7644 } else {
7645 return "data_app";
7646 }
7647 }
7648
7649 /**
7650 * Write a description of an error (crash, WTF, ANR) to the drop box.
7651 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7652 * @param process which caused the error, null means the system server
7653 * @param activity which triggered the error, null if unknown
7654 * @param parent activity related to the error, null if unknown
7655 * @param subject line related to the error, null if absent
7656 * @param report in long form describing the error, null if absent
7657 * @param logFile to include in the report, null if none
7658 * @param crashInfo giving an application stack trace, null if absent
7659 */
7660 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007661 ProcessRecord process, String processName, ActivityRecord activity,
7662 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007663 final String report, final File logFile,
7664 final ApplicationErrorReport.CrashInfo crashInfo) {
7665 // NOTE -- this must never acquire the ActivityManagerService lock,
7666 // otherwise the watchdog may be prevented from resetting the system.
7667
7668 final String dropboxTag = processClass(process) + "_" + eventType;
7669 final DropBoxManager dbox = (DropBoxManager)
7670 mContext.getSystemService(Context.DROPBOX_SERVICE);
7671
7672 // Exit early if the dropbox isn't configured to accept this report type.
7673 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7674
7675 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007676 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007677 if (activity != null) {
7678 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7679 }
7680 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7681 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7682 }
7683 if (parent != null && parent != activity) {
7684 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7685 }
7686 if (subject != null) {
7687 sb.append("Subject: ").append(subject).append("\n");
7688 }
7689 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007690 if (Debug.isDebuggerConnected()) {
7691 sb.append("Debugger: Connected\n");
7692 }
Dan Egnora455d192010-03-12 08:52:28 -08007693 sb.append("\n");
7694
7695 // Do the rest in a worker thread to avoid blocking the caller on I/O
7696 // (After this point, we shouldn't access AMS internal data structures.)
7697 Thread worker = new Thread("Error dump: " + dropboxTag) {
7698 @Override
7699 public void run() {
7700 if (report != null) {
7701 sb.append(report);
7702 }
7703 if (logFile != null) {
7704 try {
7705 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7706 } catch (IOException e) {
7707 Slog.e(TAG, "Error reading " + logFile, e);
7708 }
7709 }
7710 if (crashInfo != null && crashInfo.stackTrace != null) {
7711 sb.append(crashInfo.stackTrace);
7712 }
7713
7714 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7715 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7716 if (lines > 0) {
7717 sb.append("\n");
7718
7719 // Merge several logcat streams, and take the last N lines
7720 InputStreamReader input = null;
7721 try {
7722 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7723 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7724 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7725
7726 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7727 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7728 input = new InputStreamReader(logcat.getInputStream());
7729
7730 int num;
7731 char[] buf = new char[8192];
7732 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7733 } catch (IOException e) {
7734 Slog.e(TAG, "Error running logcat", e);
7735 } finally {
7736 if (input != null) try { input.close(); } catch (IOException e) {}
7737 }
7738 }
7739
7740 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007741 }
Dan Egnora455d192010-03-12 08:52:28 -08007742 };
7743
7744 if (process == null || process.pid == MY_PID) {
7745 worker.run(); // We may be about to die -- need to run this synchronously
7746 } else {
7747 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007748 }
7749 }
7750
7751 /**
7752 * Bring up the "unexpected error" dialog box for a crashing app.
7753 * Deal with edge cases (intercepts from instrumented applications,
7754 * ActivityController, error intent receivers, that sort of thing).
7755 * @param r the application crashing
7756 * @param crashInfo describing the failure
7757 */
7758 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007759 long timeMillis = System.currentTimeMillis();
7760 String shortMsg = crashInfo.exceptionClassName;
7761 String longMsg = crashInfo.exceptionMessage;
7762 String stackTrace = crashInfo.stackTrace;
7763 if (shortMsg != null && longMsg != null) {
7764 longMsg = shortMsg + ": " + longMsg;
7765 } else if (shortMsg != null) {
7766 longMsg = shortMsg;
7767 }
7768
Dan Egnor60d87622009-12-16 16:32:58 -08007769 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007771 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 try {
7773 String name = r != null ? r.processName : null;
7774 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007775 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007776 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007777 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 + " at watcher's request");
7779 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007780 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 }
7782 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007783 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007784 }
7785 }
7786
7787 final long origId = Binder.clearCallingIdentity();
7788
7789 // If this process is running instrumentation, finish it.
7790 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007791 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007793 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7794 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 Bundle info = new Bundle();
7796 info.putString("shortMsg", shortMsg);
7797 info.putString("longMsg", longMsg);
7798 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7799 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007800 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 }
7802
Dan Egnor60d87622009-12-16 16:32:58 -08007803 // If we can't identify the process or it's already exceeded its crash quota,
7804 // quit right away without showing a crash dialog.
7805 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007807 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 }
7809
7810 Message msg = Message.obtain();
7811 msg.what = SHOW_ERROR_MSG;
7812 HashMap data = new HashMap();
7813 data.put("result", result);
7814 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 msg.obj = data;
7816 mHandler.sendMessage(msg);
7817
7818 Binder.restoreCallingIdentity(origId);
7819 }
7820
7821 int res = result.get();
7822
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007823 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007825 if (r != null && !r.isolated) {
7826 // XXX Can't keep track of crash time for isolated processes,
7827 // since they don't have a persistent identity.
7828 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 SystemClock.uptimeMillis());
7830 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007831 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007832 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007833 }
7834 }
7835
7836 if (appErrorIntent != null) {
7837 try {
7838 mContext.startActivity(appErrorIntent);
7839 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007840 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007844
7845 Intent createAppErrorIntentLocked(ProcessRecord r,
7846 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7847 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007848 if (report == null) {
7849 return null;
7850 }
7851 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7852 result.setComponent(r.errorReportReceiver);
7853 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7854 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7855 return result;
7856 }
7857
Dan Egnorb7f03672009-12-09 16:22:32 -08007858 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7859 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007860 if (r.errorReportReceiver == null) {
7861 return null;
7862 }
7863
7864 if (!r.crashing && !r.notResponding) {
7865 return null;
7866 }
7867
Dan Egnorb7f03672009-12-09 16:22:32 -08007868 ApplicationErrorReport report = new ApplicationErrorReport();
7869 report.packageName = r.info.packageName;
7870 report.installerPackageName = r.errorReportReceiver.getPackageName();
7871 report.processName = r.processName;
7872 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007873 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007874
Dan Egnorb7f03672009-12-09 16:22:32 -08007875 if (r.crashing) {
7876 report.type = ApplicationErrorReport.TYPE_CRASH;
7877 report.crashInfo = crashInfo;
7878 } else if (r.notResponding) {
7879 report.type = ApplicationErrorReport.TYPE_ANR;
7880 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007881
Dan Egnorb7f03672009-12-09 16:22:32 -08007882 report.anrInfo.activity = r.notRespondingReport.tag;
7883 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7884 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007885 }
7886
Dan Egnorb7f03672009-12-09 16:22:32 -08007887 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007888 }
7889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007891 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 // assume our apps are happy - lazy create the list
7893 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7894
7895 synchronized (this) {
7896
7897 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007898 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7899 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7901 // This one's in trouble, so we'll generate a report for it
7902 // crashes are higher priority (in case there's a crash *and* an anr)
7903 ActivityManager.ProcessErrorStateInfo report = null;
7904 if (app.crashing) {
7905 report = app.crashingReport;
7906 } else if (app.notResponding) {
7907 report = app.notRespondingReport;
7908 }
7909
7910 if (report != null) {
7911 if (errList == null) {
7912 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7913 }
7914 errList.add(report);
7915 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007916 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 " crashing = " + app.crashing +
7918 " notResponding = " + app.notResponding);
7919 }
7920 }
7921 }
7922 }
7923
7924 return errList;
7925 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07007926
7927 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007928 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007929 if (currApp != null) {
7930 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
7931 }
7932 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007933 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
7934 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007935 } else if (adj >= ProcessList.HOME_APP_ADJ) {
7936 if (currApp != null) {
7937 currApp.lru = 0;
7938 }
7939 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007940 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07007941 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
7942 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
7943 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
7944 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
7945 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
7946 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
7947 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
7948 } else {
7949 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
7950 }
7951 }
7952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007954 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 // Lazy instantiation of list
7956 List<ActivityManager.RunningAppProcessInfo> runList = null;
7957 synchronized (this) {
7958 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007959 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7960 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
7962 // Generate process state info for running application
7963 ActivityManager.RunningAppProcessInfo currApp =
7964 new ActivityManager.RunningAppProcessInfo(app.processName,
7965 app.pid, app.getPackageList());
Dianne Hackborneb034652009-09-07 00:49:58 -07007966 currApp.uid = app.info.uid;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007967 if (mHeavyWeightProcess == app) {
Dianne Hackborn482566e2010-09-03 12:51:28 -07007968 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
Dianne Hackbornbaf42c62010-06-24 11:23:39 -07007969 }
Dianne Hackborn42499172010-10-15 18:45:07 -07007970 if (app.persistent) {
7971 currApp.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
7972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 int adj = app.curAdj;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007974 currApp.importance = oomAdjToImportance(adj, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007975 currApp.importanceReasonCode = app.adjTypeCode;
7976 if (app.adjSource instanceof ProcessRecord) {
7977 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07007978 currApp.importanceReasonImportance = oomAdjToImportance(
7979 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007980 } else if (app.adjSource instanceof ActivityRecord) {
7981 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07007982 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
7983 }
7984 if (app.adjTarget instanceof ComponentName) {
7985 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
7986 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007987 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 // + " lru=" + currApp.lru);
7989 if (runList == null) {
7990 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
7991 }
7992 runList.add(currApp);
7993 }
7994 }
7995 }
7996 return runList;
7997 }
7998
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07007999 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008000 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008001 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8002 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8003 if (runningApps != null && runningApps.size() > 0) {
8004 Set<String> extList = new HashSet<String>();
8005 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8006 if (app.pkgList != null) {
8007 for (String pkg : app.pkgList) {
8008 extList.add(pkg);
8009 }
8010 }
8011 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008012 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008013 for (String pkg : extList) {
8014 try {
8015 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8016 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8017 retList.add(info);
8018 }
8019 } catch (RemoteException e) {
8020 }
8021 }
8022 }
8023 return retList;
8024 }
8025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 @Override
8027 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008028 if (checkCallingPermission(android.Manifest.permission.DUMP)
8029 != PackageManager.PERMISSION_GRANTED) {
8030 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8031 + Binder.getCallingPid()
8032 + ", uid=" + Binder.getCallingUid()
8033 + " without permission "
8034 + android.Manifest.permission.DUMP);
8035 return;
8036 }
8037
8038 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008039 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008040 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008041
8042 int opti = 0;
8043 while (opti < args.length) {
8044 String opt = args[opti];
8045 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8046 break;
8047 }
8048 opti++;
8049 if ("-a".equals(opt)) {
8050 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008051 } else if ("-c".equals(opt)) {
8052 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008053 } else if ("-h".equals(opt)) {
8054 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008055 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008056 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008057 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008058 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8059 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8060 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008061 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008062 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008063 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008064 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008065 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008066 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008067 pw.println(" all: dump all activities");
8068 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008069 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008070 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8071 pw.println(" a partial substring in a component name, a");
8072 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008073 pw.println(" -a: include all available server state.");
8074 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008076 } else {
8077 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008079 }
8080
8081 // Is the caller requesting to dump a particular piece of data?
8082 if (opti < args.length) {
8083 String cmd = args[opti];
8084 opti++;
8085 if ("activities".equals(cmd) || "a".equals(cmd)) {
8086 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008087 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008089 return;
8090 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008091 String[] newArgs;
8092 String name;
8093 if (opti >= args.length) {
8094 name = null;
8095 newArgs = EMPTY_STRING_ARRAY;
8096 } else {
8097 name = args[opti];
8098 opti++;
8099 newArgs = new String[args.length - opti];
8100 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8101 args.length - opti);
8102 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008103 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008104 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008105 }
8106 return;
8107 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008108 String[] newArgs;
8109 String name;
8110 if (opti >= args.length) {
8111 name = null;
8112 newArgs = EMPTY_STRING_ARRAY;
8113 } else {
8114 name = args[opti];
8115 opti++;
8116 newArgs = new String[args.length - opti];
8117 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8118 args.length - opti);
8119 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008120 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008121 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008122 }
8123 return;
8124 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008125 String[] newArgs;
8126 String name;
8127 if (opti >= args.length) {
8128 name = null;
8129 newArgs = EMPTY_STRING_ARRAY;
8130 } else {
8131 name = args[opti];
8132 opti++;
8133 newArgs = new String[args.length - opti];
8134 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8135 args.length - opti);
8136 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008137 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008138 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008139 }
8140 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008141 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8142 synchronized (this) {
8143 dumpOomLocked(fd, pw, args, opti, true);
8144 }
8145 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008146 } else if ("provider".equals(cmd)) {
8147 String[] newArgs;
8148 String name;
8149 if (opti >= args.length) {
8150 name = null;
8151 newArgs = EMPTY_STRING_ARRAY;
8152 } else {
8153 name = args[opti];
8154 opti++;
8155 newArgs = new String[args.length - opti];
8156 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8157 }
8158 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8159 pw.println("No providers match: " + name);
8160 pw.println("Use -h for help.");
8161 }
8162 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008163 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8164 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008165 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008166 }
8167 return;
8168 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008169 String[] newArgs;
8170 String name;
8171 if (opti >= args.length) {
8172 name = null;
8173 newArgs = EMPTY_STRING_ARRAY;
8174 } else {
8175 name = args[opti];
8176 opti++;
8177 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008178 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8179 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008180 }
8181 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8182 pw.println("No services match: " + name);
8183 pw.println("Use -h for help.");
8184 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008185 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008186 } else if ("package".equals(cmd)) {
8187 String[] newArgs;
8188 if (opti >= args.length) {
8189 pw.println("package: no package name specified");
8190 pw.println("Use -h for help.");
8191 return;
8192 } else {
8193 dumpPackage = 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 args = newArgs;
8199 opti = 0;
8200 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008201 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8202 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008203 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008204 }
8205 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008206 } else {
8207 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008208 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8209 pw.println("Bad activity command, or no activities match: " + cmd);
8210 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008211 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008212 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008214 }
8215
8216 // No piece of data specified, dump everything.
8217 synchronized (this) {
8218 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008219 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008220 if (needSep) {
8221 pw.println(" ");
8222 }
8223 if (dumpAll) {
8224 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008225 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008226 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008227 if (needSep) {
8228 pw.println(" ");
8229 }
8230 if (dumpAll) {
8231 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008232 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008233 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008234 if (needSep) {
8235 pw.println(" ");
8236 }
8237 if (dumpAll) {
8238 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008239 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008240 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008241 if (needSep) {
8242 pw.println(" ");
8243 }
8244 if (dumpAll) {
8245 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008246 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008247 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008248 if (needSep) {
8249 pw.println(" ");
8250 }
8251 if (dumpAll) {
8252 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008253 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008254 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008255 }
8256 }
8257
8258 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008259 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008260 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8261 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008262 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8263 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008264 pw.println(" ");
8265 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008266 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8267 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008268 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008270 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008271 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008272 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008273 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008274 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008276 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008277 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008278 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008279 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008280 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8281 pw.println(" ");
8282 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008283 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008284 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008285 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008286 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008287 pw.println(" ");
8288 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008289 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008290 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008293 pw.println(" ");
Dianne Hackborncbb722e2012-02-07 18:33:49 -08008294 if (mMainStack.mPausingActivities.size() > 0) {
8295 pw.println(" mPausingActivities: " + Arrays.toString(
8296 mMainStack.mPausingActivities.toArray()));
8297 }
8298 if (mMainStack.mInputPausedActivities.size() > 0) {
8299 pw.println(" mInputPausedActivities: " + Arrays.toString(
8300 mMainStack.mInputPausedActivities.toArray()));
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008301 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008302 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008303 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008304 if (dumpAll) {
8305 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8306 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008307 pw.println(" mDismissKeyguardOnNextActivity: "
8308 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008310
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008311 if (mRecentTasks.size() > 0) {
8312 pw.println();
8313 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008314
8315 final int N = mRecentTasks.size();
8316 for (int i=0; i<N; i++) {
8317 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008318 if (dumpPackage != null) {
8319 if (tr.realActivity == null ||
8320 !dumpPackage.equals(tr.realActivity)) {
8321 continue;
8322 }
8323 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008324 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8325 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008326 if (dumpAll) {
8327 mRecentTasks.get(i).dump(pw, " ");
8328 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008329 }
8330 }
8331
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008332 if (dumpAll) {
8333 pw.println(" ");
8334 pw.println(" mCurTask: " + mCurTask);
8335 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008336
8337 return true;
8338 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008339
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008341 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008342 boolean needSep = false;
8343 int numPers = 0;
8344
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008345 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8346
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008347 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8349 final int NA = procs.size();
8350 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008351 ProcessRecord r = procs.valueAt(ia);
8352 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8353 continue;
8354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355 if (!needSep) {
8356 pw.println(" All known processes:");
8357 needSep = true;
8358 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008359 pw.print(r.persistent ? " *PERS*" : " *APP*");
8360 pw.print(" UID "); pw.print(procs.keyAt(ia));
8361 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 r.dump(pw, " ");
8363 if (r.persistent) {
8364 numPers++;
8365 }
8366 }
8367 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008368 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008369
8370 if (mIsolatedProcesses.size() > 0) {
8371 if (needSep) pw.println(" ");
8372 needSep = true;
8373 pw.println(" Isolated process list (sorted by uid):");
8374 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8375 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8376 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8377 continue;
8378 }
8379 pw.println(String.format("%sIsolated #%2d: %s",
8380 " ", i, r.toString()));
8381 }
8382 }
8383
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008384 if (mLruProcesses.size() > 0) {
8385 if (needSep) pw.println(" ");
8386 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008387 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008388 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008389 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008390 needSep = true;
8391 }
8392
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008393 if (dumpAll) {
8394 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008395 boolean printed = false;
8396 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8397 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8398 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8399 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008400 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008401 if (!printed) {
8402 if (needSep) pw.println(" ");
8403 needSep = true;
8404 pw.println(" PID mappings:");
8405 printed = true;
8406 }
8407 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8408 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 }
8410 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008411 }
8412
8413 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008414 synchronized (mPidsSelfLocked) {
8415 boolean printed = false;
8416 for (int i=0; i<mForegroundProcesses.size(); i++) {
8417 ProcessRecord r = mPidsSelfLocked.get(
8418 mForegroundProcesses.valueAt(i).pid);
8419 if (dumpPackage != null && (r == null
8420 || !dumpPackage.equals(r.info.packageName))) {
8421 continue;
8422 }
8423 if (!printed) {
8424 if (needSep) pw.println(" ");
8425 needSep = true;
8426 pw.println(" Foreground Processes:");
8427 printed = true;
8428 }
8429 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8430 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008433 }
8434
8435 if (mPersistentStartingProcesses.size() > 0) {
8436 if (needSep) pw.println(" ");
8437 needSep = true;
8438 pw.println(" Persisent processes that are starting:");
8439 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008440 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008443 if (mRemovedProcesses.size() > 0) {
8444 if (needSep) pw.println(" ");
8445 needSep = true;
8446 pw.println(" Processes that are being removed:");
8447 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008448 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 }
8450
8451 if (mProcessesOnHold.size() > 0) {
8452 if (needSep) pw.println(" ");
8453 needSep = true;
8454 pw.println(" Processes that are on old until the system is ready:");
8455 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008456 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008459 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008460
8461 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008462 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008463 long now = SystemClock.uptimeMillis();
8464 for (Map.Entry<String, SparseArray<Long>> procs
8465 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008466 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008467 SparseArray<Long> uids = procs.getValue();
8468 final int N = uids.size();
8469 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008470 int puid = uids.keyAt(i);
8471 ProcessRecord r = mProcessNames.get(pname, puid);
8472 if (dumpPackage != null && (r == null
8473 || !dumpPackage.equals(r.info.packageName))) {
8474 continue;
8475 }
8476 if (!printed) {
8477 if (needSep) pw.println(" ");
8478 needSep = true;
8479 pw.println(" Time since processes crashed:");
8480 printed = true;
8481 }
8482 pw.print(" Process "); pw.print(pname);
8483 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008484 pw.print(": last crashed ");
8485 pw.print((now-uids.valueAt(i)));
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008486 pw.println(" ms ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008487 }
8488 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008490
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008491 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008492 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008493 for (Map.Entry<String, SparseArray<Long>> procs
8494 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008495 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008496 SparseArray<Long> uids = procs.getValue();
8497 final int N = uids.size();
8498 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008499 int puid = uids.keyAt(i);
8500 ProcessRecord r = mProcessNames.get(pname, puid);
8501 if (dumpPackage != null && (r == null
8502 || !dumpPackage.equals(r.info.packageName))) {
8503 continue;
8504 }
8505 if (!printed) {
8506 if (needSep) pw.println(" ");
8507 needSep = true;
8508 pw.println(" Bad processes:");
8509 }
8510 pw.print(" Bad process "); pw.print(pname);
8511 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008512 pw.print(": crashed at time ");
8513 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008514 }
8515 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008518 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008519 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008520 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008521 if (dumpAll) {
8522 StringBuilder sb = new StringBuilder(128);
8523 sb.append(" mPreviousProcessVisibleTime: ");
8524 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8525 pw.println(sb);
8526 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008527 if (mHeavyWeightProcess != null) {
8528 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8529 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008530 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008531 if (dumpAll) {
8532 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008533 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008534 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008535 for (Map.Entry<String, Integer> entry
8536 : mCompatModePackages.getPackages().entrySet()) {
8537 String pkg = entry.getKey();
8538 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008539 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8540 continue;
8541 }
8542 if (!printed) {
8543 pw.println(" mScreenCompatPackages:");
8544 printed = true;
8545 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008546 pw.print(" "); pw.print(pkg); pw.print(": ");
8547 pw.print(mode); pw.println();
8548 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008549 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008550 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8552 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8553 || mOrigWaitForDebugger) {
8554 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8555 + " mDebugTransient=" + mDebugTransient
8556 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8557 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008558 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8559 || mProfileFd != null) {
8560 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8561 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8562 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8563 + mAutoStopProfiler);
8564 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565 if (mAlwaysFinishActivities || mController != null) {
8566 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8567 + " mController=" + mController);
8568 }
8569 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008572 + " mProcessesReady=" + mProcessesReady
8573 + " mSystemReady=" + mSystemReady);
8574 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 + " mBooted=" + mBooted
8576 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008577 pw.print(" mLastPowerCheckRealtime=");
8578 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8579 pw.println("");
8580 pw.print(" mLastPowerCheckUptime=");
8581 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8582 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008583 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8584 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008585 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008586 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8587 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008589
8590 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 }
8592
Dianne Hackborn287952c2010-09-22 22:34:31 -07008593 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008594 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008595 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008596 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008597 long now = SystemClock.uptimeMillis();
8598 for (int i=0; i<mProcessesToGc.size(); i++) {
8599 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8601 continue;
8602 }
8603 if (!printed) {
8604 if (needSep) pw.println(" ");
8605 needSep = true;
8606 pw.println(" Processes that are waiting to GC:");
8607 printed = true;
8608 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008609 pw.print(" Process "); pw.println(proc);
8610 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8611 pw.print(", last gced=");
8612 pw.print(now-proc.lastRequestedGc);
8613 pw.print(" ms ago, last lowMem=");
8614 pw.print(now-proc.lastLowMemory);
8615 pw.println(" ms ago");
8616
8617 }
8618 }
8619 return needSep;
8620 }
8621
8622 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8623 int opti, boolean dumpAll) {
8624 boolean needSep = false;
8625
8626 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008627 if (needSep) pw.println(" ");
8628 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008629 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008630 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008631 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008632 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8633 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8634 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8635 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8636 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008637 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008638 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008639 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008640 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008641 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008642 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008643
8644 if (needSep) pw.println(" ");
8645 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008646 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008647 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008648 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008649 needSep = true;
8650 }
8651
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008653
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008654 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008655 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008656 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008657 if (mHeavyWeightProcess != null) {
8658 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8659 }
8660
8661 return true;
8662 }
8663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 /**
8665 * There are three ways to call this:
8666 * - no service specified: dump all the services
8667 * - a flattened component name that matched an existing service was specified as the
8668 * first arg: dump that one service
8669 * - the first arg isn't the flattened component name of an existing service:
8670 * dump all services whose component contains the first arg as a substring
8671 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008672 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8673 int opti, boolean dumpAll) {
8674 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008675
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008677 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008678 try {
8679 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8680 for (UserInfo user : users) {
8681 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8682 services.add(r1);
8683 }
8684 }
8685 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008686 }
8687 }
8688 } else {
8689 ComponentName componentName = name != null
8690 ? ComponentName.unflattenFromString(name) : null;
8691 int objectId = 0;
8692 if (componentName == null) {
8693 // Not a '/' separated full component name; maybe an object ID?
8694 try {
8695 objectId = Integer.parseInt(name, 16);
8696 name = null;
8697 componentName = null;
8698 } catch (RuntimeException e) {
8699 }
8700 }
8701
8702 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008703 try {
8704 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8705 for (UserInfo user : users) {
8706 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8707 if (componentName != null) {
8708 if (r1.name.equals(componentName)) {
8709 services.add(r1);
8710 }
8711 } else if (name != null) {
8712 if (r1.name.flattenToString().contains(name)) {
8713 services.add(r1);
8714 }
8715 } else if (System.identityHashCode(r1) == objectId) {
8716 services.add(r1);
8717 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008718 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008719 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008720 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 }
8722 }
8723 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008724
8725 if (services.size() <= 0) {
8726 return false;
8727 }
8728
8729 boolean needSep = false;
8730 for (int i=0; i<services.size(); i++) {
8731 if (needSep) {
8732 pw.println();
8733 }
8734 needSep = true;
8735 dumpService("", fd, pw, services.get(i), args, dumpAll);
8736 }
8737 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 }
8739
8740 /**
8741 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8742 * there is a thread associated with the service.
8743 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008744 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8745 final ServiceRecord r, String[] args, boolean dumpAll) {
8746 String innerPrefix = prefix + " ";
8747 synchronized (this) {
8748 pw.print(prefix); pw.print("SERVICE ");
8749 pw.print(r.shortName); pw.print(" ");
8750 pw.print(Integer.toHexString(System.identityHashCode(r)));
8751 pw.print(" pid=");
8752 if (r.app != null) pw.println(r.app.pid);
8753 else pw.println("(not running)");
8754 if (dumpAll) {
8755 r.dump(pw, innerPrefix);
8756 }
8757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008758 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008759 pw.print(prefix); pw.println(" Client:");
8760 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008762 TransferPipe tp = new TransferPipe();
8763 try {
8764 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8765 tp.setBufferPrefix(prefix + " ");
8766 tp.go(fd);
8767 } finally {
8768 tp.kill();
8769 }
8770 } catch (IOException e) {
8771 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008773 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 }
8775 }
8776 }
8777
Marco Nelissen18cb2872011-11-15 11:19:53 -08008778 /**
8779 * There are three ways to call this:
8780 * - no provider specified: dump all the providers
8781 * - a flattened component name that matched an existing provider was specified as the
8782 * first arg: dump that one provider
8783 * - the first arg isn't the flattened component name of an existing provider:
8784 * dump all providers whose component contains the first arg as a substring
8785 */
8786 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8787 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008788 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008789 }
8790
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008791 static class ItemMatcher {
8792 ArrayList<ComponentName> components;
8793 ArrayList<String> strings;
8794 ArrayList<Integer> objects;
8795 boolean all;
8796
8797 ItemMatcher() {
8798 all = true;
8799 }
8800
8801 void build(String name) {
8802 ComponentName componentName = ComponentName.unflattenFromString(name);
8803 if (componentName != null) {
8804 if (components == null) {
8805 components = new ArrayList<ComponentName>();
8806 }
8807 components.add(componentName);
8808 all = false;
8809 } else {
8810 int objectId = 0;
8811 // Not a '/' separated full component name; maybe an object ID?
8812 try {
8813 objectId = Integer.parseInt(name, 16);
8814 if (objects == null) {
8815 objects = new ArrayList<Integer>();
8816 }
8817 objects.add(objectId);
8818 all = false;
8819 } catch (RuntimeException e) {
8820 // Not an integer; just do string match.
8821 if (strings == null) {
8822 strings = new ArrayList<String>();
8823 }
8824 strings.add(name);
8825 all = false;
8826 }
8827 }
8828 }
8829
8830 int build(String[] args, int opti) {
8831 for (; opti<args.length; opti++) {
8832 String name = args[opti];
8833 if ("--".equals(name)) {
8834 return opti+1;
8835 }
8836 build(name);
8837 }
8838 return opti;
8839 }
8840
8841 boolean match(Object object, ComponentName comp) {
8842 if (all) {
8843 return true;
8844 }
8845 if (components != null) {
8846 for (int i=0; i<components.size(); i++) {
8847 if (components.get(i).equals(comp)) {
8848 return true;
8849 }
8850 }
8851 }
8852 if (objects != null) {
8853 for (int i=0; i<objects.size(); i++) {
8854 if (System.identityHashCode(object) == objects.get(i)) {
8855 return true;
8856 }
8857 }
8858 }
8859 if (strings != null) {
8860 String flat = comp.flattenToString();
8861 for (int i=0; i<strings.size(); i++) {
8862 if (flat.contains(strings.get(i))) {
8863 return true;
8864 }
8865 }
8866 }
8867 return false;
8868 }
8869 }
8870
Dianne Hackborn625ac272010-09-17 18:29:22 -07008871 /**
8872 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008873 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008874 * - the cmd arg isn't the flattened component name of an existing activity:
8875 * dump all activity whose component contains the cmd as a substring
8876 * - A hex number of the ActivityRecord object instance.
8877 */
8878 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8879 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008880 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008881
8882 if ("all".equals(name)) {
8883 synchronized (this) {
8884 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008885 activities.add(r1);
8886 }
8887 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008888 } else if ("top".equals(name)) {
8889 synchronized (this) {
8890 final int N = mMainStack.mHistory.size();
8891 if (N > 0) {
8892 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8893 }
8894 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008895 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008896 ItemMatcher matcher = new ItemMatcher();
8897 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008898
8899 synchronized (this) {
8900 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008901 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008902 activities.add(r1);
8903 }
8904 }
8905 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008906 }
8907
8908 if (activities.size() <= 0) {
8909 return false;
8910 }
8911
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008912 String[] newArgs = new String[args.length - opti];
8913 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8914
Dianne Hackborn30d71892010-12-11 10:37:55 -08008915 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008916 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08008917 for (int i=activities.size()-1; i>=0; i--) {
8918 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008919 if (needSep) {
8920 pw.println();
8921 }
8922 needSep = true;
8923 synchronized (this) {
8924 if (lastTask != r.task) {
8925 lastTask = r.task;
8926 pw.print("TASK "); pw.print(lastTask.affinity);
8927 pw.print(" id="); pw.println(lastTask.taskId);
8928 if (dumpAll) {
8929 lastTask.dump(pw, " ");
8930 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008931 }
8932 }
8933 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008934 }
8935 return true;
8936 }
8937
8938 /**
8939 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
8940 * there is a thread associated with the activity.
8941 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08008942 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008943 final ActivityRecord r, String[] args, boolean dumpAll) {
8944 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08008945 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008946 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
8947 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
8948 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08008949 if (r.app != null) pw.println(r.app.pid);
8950 else pw.println("(not running)");
8951 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008952 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008953 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008954 }
8955 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008956 // flush anything that is already in the PrintWriter since the thread is going
8957 // to write to the file descriptor directly
8958 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07008959 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008960 TransferPipe tp = new TransferPipe();
8961 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08008962 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
8963 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008964 tp.go(fd);
8965 } finally {
8966 tp.kill();
8967 }
8968 } catch (IOException e) {
8969 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07008970 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008971 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008972 }
8973 }
8974 }
8975
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008976 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008977 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008978 boolean needSep = false;
8979
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008980 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008981 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008982 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008983 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 Iterator it = mRegisteredReceivers.values().iterator();
8985 while (it.hasNext()) {
8986 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008987 if (dumpPackage != null && (r.app == null ||
8988 !dumpPackage.equals(r.app.info.packageName))) {
8989 continue;
8990 }
8991 if (!printed) {
8992 pw.println(" Registered Receivers:");
8993 needSep = true;
8994 printed = true;
8995 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008996 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 r.dump(pw, " ");
8998 }
8999 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009000
9001 if (mReceiverResolver.dump(pw, needSep ?
9002 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9003 " ", dumpPackage, false)) {
9004 needSep = true;
9005 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009007
9008 for (BroadcastQueue q : mBroadcastQueues) {
9009 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009012 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009014 if (mStickyBroadcasts != null && dumpPackage == null) {
9015 if (needSep) {
9016 pw.println();
9017 }
9018 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009019 pw.println(" Sticky broadcasts:");
9020 StringBuilder sb = new StringBuilder(128);
9021 for (Map.Entry<String, ArrayList<Intent>> ent
9022 : mStickyBroadcasts.entrySet()) {
9023 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009024 if (dumpAll) {
9025 pw.println(":");
9026 ArrayList<Intent> intents = ent.getValue();
9027 final int N = intents.size();
9028 for (int i=0; i<N; i++) {
9029 sb.setLength(0);
9030 sb.append(" Intent: ");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009031 intents.get(i).toShortString(sb, false, true, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 pw.println(sb.toString());
9033 Bundle bundle = intents.get(i).getExtras();
9034 if (bundle != null) {
9035 pw.print(" ");
9036 pw.println(bundle.toString());
9037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009039 } else {
9040 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 }
9042 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043 needSep = true;
9044 }
9045
9046 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009047 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009048 for (BroadcastQueue queue : mBroadcastQueues) {
9049 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9050 + queue.mBroadcastsScheduled);
9051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 pw.println(" mHandler:");
9053 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009054 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009056
9057 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058 }
9059
Marco Nelissen18cb2872011-11-15 11:19:53 -08009060 /**
9061 * Prints a list of ServiceRecords (dumpsys activity services)
9062 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009063 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009064 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009065 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009067 ItemMatcher matcher = new ItemMatcher();
9068 matcher.build(args, opti);
9069
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009070 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009071 try {
9072 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9073 for (UserInfo user : users) {
9074 if (mServiceMap.getAllServices(user.id).size() > 0) {
9075 boolean printed = false;
9076 long nowReal = SystemClock.elapsedRealtime();
9077 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9078 user.id).iterator();
9079 needSep = false;
9080 while (it.hasNext()) {
9081 ServiceRecord r = it.next();
9082 if (!matcher.match(r, r.name)) {
9083 continue;
9084 }
9085 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9086 continue;
9087 }
9088 if (!printed) {
9089 pw.println(" Active services:");
9090 printed = true;
9091 }
9092 if (needSep) {
9093 pw.println();
9094 }
9095 pw.print(" * ");
9096 pw.println(r);
9097 if (dumpAll) {
9098 r.dump(pw, " ");
9099 needSep = true;
9100 } else {
9101 pw.print(" app=");
9102 pw.println(r.app);
9103 pw.print(" created=");
9104 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9105 pw.print(" started=");
9106 pw.print(r.startRequested);
9107 pw.print(" connections=");
9108 pw.println(r.connections.size());
9109 if (r.connections.size() > 0) {
9110 pw.println(" Connections:");
9111 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9112 for (int i = 0; i < clist.size(); i++) {
9113 ConnectionRecord conn = clist.get(i);
9114 pw.print(" ");
9115 pw.print(conn.binding.intent.intent.getIntent()
9116 .toShortString(false, false, false));
9117 pw.print(" -> ");
9118 ProcessRecord proc = conn.binding.client;
9119 pw.println(proc != null ? proc.toShortString() : "null");
9120 }
9121 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009122 }
9123 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009124 if (dumpClient && r.app != null && r.app.thread != null) {
9125 pw.println(" Client:");
9126 pw.flush();
9127 try {
9128 TransferPipe tp = new TransferPipe();
9129 try {
9130 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9131 r, args);
9132 tp.setBufferPrefix(" ");
9133 // Short timeout, since blocking here can
9134 // deadlock with the application.
9135 tp.go(fd, 2000);
9136 } finally {
9137 tp.kill();
9138 }
9139 } catch (IOException e) {
9140 pw.println(" Failure while dumping the service: " + e);
9141 } catch (RemoteException e) {
9142 pw.println(" Got a RemoteException while dumping the service");
9143 }
9144 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009145 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009146 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009147 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009150 } catch (RemoteException re) {
9151
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009154 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009155 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009156 for (int i=0; i<mPendingServices.size(); i++) {
9157 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009158 if (!matcher.match(r, r.name)) {
9159 continue;
9160 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009161 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9162 continue;
9163 }
9164 if (!printed) {
9165 if (needSep) pw.println(" ");
9166 needSep = true;
9167 pw.println(" Pending services:");
9168 printed = true;
9169 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009170 pw.print(" * Pending "); pw.println(r);
9171 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009172 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009173 needSep = true;
9174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009176 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009177 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009178 for (int i=0; i<mRestartingServices.size(); i++) {
9179 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009180 if (!matcher.match(r, r.name)) {
9181 continue;
9182 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009183 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9184 continue;
9185 }
9186 if (!printed) {
9187 if (needSep) pw.println(" ");
9188 needSep = true;
9189 pw.println(" Restarting services:");
9190 printed = true;
9191 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009192 pw.print(" * Restarting "); pw.println(r);
9193 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009195 needSep = true;
9196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009197
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009198 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009200 for (int i=0; i<mStoppingServices.size(); i++) {
9201 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009202 if (!matcher.match(r, r.name)) {
9203 continue;
9204 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009205 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9206 continue;
9207 }
9208 if (!printed) {
9209 if (needSep) pw.println(" ");
9210 needSep = true;
9211 pw.println(" Stopping services:");
9212 printed = true;
9213 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009214 pw.print(" * Stopping "); pw.println(r);
9215 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009217 needSep = true;
9218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009222 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009223 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009224 = mServiceConnections.values().iterator();
9225 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009226 ArrayList<ConnectionRecord> r = it.next();
9227 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009228 ConnectionRecord cr = r.get(i);
9229 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9230 continue;
9231 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009232 if (dumpPackage != null && (cr.binding.client == null
9233 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9234 continue;
9235 }
9236 if (!printed) {
9237 if (needSep) pw.println(" ");
9238 needSep = true;
9239 pw.println(" Connection bindings to services:");
9240 printed = true;
9241 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009242 pw.print(" * "); pw.println(cr);
9243 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247 }
9248 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009249
9250 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 }
9252
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009253 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009254 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009255 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009256
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009257 ItemMatcher matcher = new ItemMatcher();
9258 matcher.build(args, opti);
9259
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009260 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009261
9262 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009263
9264 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009265 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009266 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009267 ContentProviderRecord r = mLaunchingProviders.get(i);
9268 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9269 continue;
9270 }
9271 if (!printed) {
9272 if (needSep) pw.println(" ");
9273 needSep = true;
9274 pw.println(" Launching content providers:");
9275 printed = true;
9276 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009277 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009278 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009279 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009280 }
9281
9282 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009283 if (needSep) pw.println();
9284 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009285 pw.println("Granted Uri Permissions:");
9286 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9287 int uid = mGrantedUriPermissions.keyAt(i);
9288 HashMap<Uri, UriPermission> perms
9289 = mGrantedUriPermissions.valueAt(i);
9290 pw.print(" * UID "); pw.print(uid);
9291 pw.println(" holds:");
9292 for (UriPermission perm : perms.values()) {
9293 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009294 if (dumpAll) {
9295 perm.dump(pw, " ");
9296 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009297 }
9298 }
9299 needSep = true;
9300 }
9301
9302 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 }
9304
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009306 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009307 boolean needSep = false;
9308
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009309 if (mIntentSenderRecords.size() > 0) {
9310 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009311 Iterator<WeakReference<PendingIntentRecord>> it
9312 = mIntentSenderRecords.values().iterator();
9313 while (it.hasNext()) {
9314 WeakReference<PendingIntentRecord> ref = it.next();
9315 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009316 if (dumpPackage != null && (rec == null
9317 || !dumpPackage.equals(rec.key.packageName))) {
9318 continue;
9319 }
9320 if (!printed) {
9321 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9322 printed = true;
9323 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009324 needSep = true;
9325 if (rec != null) {
9326 pw.print(" * "); pw.println(rec);
9327 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009330 } else {
9331 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 }
9333 }
9334 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009335
9336 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 }
9338
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009339 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009340 String prefix, String label, boolean complete, boolean brief, boolean client,
9341 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009343 boolean needNL = false;
9344 final String innerPrefix = prefix + " ";
9345 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009348 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9349 continue;
9350 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009351 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009352 if (needNL) {
9353 pw.println(" ");
9354 needNL = false;
9355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356 if (lastTask != r.task) {
9357 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009358 pw.print(prefix);
9359 pw.print(full ? "* " : " ");
9360 pw.println(lastTask);
9361 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009362 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009363 } else if (complete) {
9364 // Complete + brief == give a summary. Isn't that obvious?!?
9365 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009366 pw.print(prefix); pw.print(" ");
9367 pw.println(lastTask.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009368 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009370 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009371 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9372 pw.print(" #"); pw.print(i); pw.print(": ");
9373 pw.println(r);
9374 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009375 r.dump(pw, innerPrefix);
9376 } else if (complete) {
9377 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009378 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009379 if (r.app != null) {
9380 pw.print(innerPrefix); pw.println(r.app);
9381 }
9382 }
9383 if (client && r.app != null && r.app.thread != null) {
9384 // flush anything that is already in the PrintWriter since the thread is going
9385 // to write to the file descriptor directly
9386 pw.flush();
9387 try {
9388 TransferPipe tp = new TransferPipe();
9389 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009390 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9391 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009392 // Short timeout, since blocking here can
9393 // deadlock with the application.
9394 tp.go(fd, 2000);
9395 } finally {
9396 tp.kill();
9397 }
9398 } catch (IOException e) {
9399 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9400 } catch (RemoteException e) {
9401 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9402 }
9403 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009405 }
9406 }
9407
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009408 private static String buildOomTag(String prefix, String space, int val, int base) {
9409 if (val == base) {
9410 if (space == null) return prefix;
9411 return prefix + " ";
9412 }
9413 return prefix + "+" + Integer.toString(val-base);
9414 }
9415
9416 private static final int dumpProcessList(PrintWriter pw,
9417 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009418 String prefix, String normalLabel, String persistentLabel,
9419 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009421 final int N = list.size()-1;
9422 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009424 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9425 continue;
9426 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009427 pw.println(String.format("%s%s #%2d: %s",
9428 prefix, (r.persistent ? persistentLabel : normalLabel),
9429 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009430 if (r.persistent) {
9431 numPers++;
9432 }
9433 }
9434 return numPers;
9435 }
9436
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009437 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009438 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009439 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009440 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009441
Dianne Hackborn905577f2011-09-07 18:31:28 -07009442 ArrayList<Pair<ProcessRecord, Integer>> list
9443 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9444 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009445 ProcessRecord r = origList.get(i);
9446 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9447 continue;
9448 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009449 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9450 }
9451
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009452 if (list.size() <= 0) {
9453 return false;
9454 }
9455
Dianne Hackborn905577f2011-09-07 18:31:28 -07009456 Comparator<Pair<ProcessRecord, Integer>> comparator
9457 = new Comparator<Pair<ProcessRecord, Integer>>() {
9458 @Override
9459 public int compare(Pair<ProcessRecord, Integer> object1,
9460 Pair<ProcessRecord, Integer> object2) {
9461 if (object1.first.setAdj != object2.first.setAdj) {
9462 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9463 }
9464 if (object1.second.intValue() != object2.second.intValue()) {
9465 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9466 }
9467 return 0;
9468 }
9469 };
9470
9471 Collections.sort(list, comparator);
9472
Dianne Hackborn287952c2010-09-22 22:34:31 -07009473 final long curRealtime = SystemClock.elapsedRealtime();
9474 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9475 final long curUptime = SystemClock.uptimeMillis();
9476 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9477
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009478 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009479 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009480 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009481 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009482 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009483 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9484 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009485 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9486 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009487 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9488 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009489 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9490 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009491 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009492 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009493 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9494 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9495 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9496 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9497 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9498 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9499 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9500 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009501 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9502 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009503 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9504 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009505 } else {
9506 oomAdj = Integer.toString(r.setAdj);
9507 }
9508 String schedGroup;
9509 switch (r.setSchedGroup) {
9510 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9511 schedGroup = "B";
9512 break;
9513 case Process.THREAD_GROUP_DEFAULT:
9514 schedGroup = "F";
9515 break;
9516 default:
9517 schedGroup = Integer.toString(r.setSchedGroup);
9518 break;
9519 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009520 String foreground;
9521 if (r.foregroundActivities) {
9522 foreground = "A";
9523 } else if (r.foregroundServices) {
9524 foreground = "S";
9525 } else {
9526 foreground = " ";
9527 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009528 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009529 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009530 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9531 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009532 if (r.adjSource != null || r.adjTarget != null) {
9533 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009534 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009535 if (r.adjTarget instanceof ComponentName) {
9536 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9537 } else if (r.adjTarget != null) {
9538 pw.print(r.adjTarget.toString());
9539 } else {
9540 pw.print("{null}");
9541 }
9542 pw.print("<=");
9543 if (r.adjSource instanceof ProcessRecord) {
9544 pw.print("Proc{");
9545 pw.print(((ProcessRecord)r.adjSource).toShortString());
9546 pw.println("}");
9547 } else if (r.adjSource != null) {
9548 pw.println(r.adjSource.toString());
9549 } else {
9550 pw.println("{null}");
9551 }
9552 }
9553 if (inclDetails) {
9554 pw.print(prefix);
9555 pw.print(" ");
9556 pw.print("oom: max="); pw.print(r.maxAdj);
9557 pw.print(" hidden="); pw.print(r.hiddenAdj);
9558 pw.print(" curRaw="); pw.print(r.curRawAdj);
9559 pw.print(" setRaw="); pw.print(r.setRawAdj);
9560 pw.print(" cur="); pw.print(r.curAdj);
9561 pw.print(" set="); pw.println(r.setAdj);
9562 pw.print(prefix);
9563 pw.print(" ");
9564 pw.print("keeping="); pw.print(r.keeping);
9565 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009566 pw.print(" empty="); pw.print(r.empty);
9567 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009568
9569 if (!r.keeping) {
9570 if (r.lastWakeTime != 0) {
9571 long wtime;
9572 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9573 synchronized (stats) {
9574 wtime = stats.getProcessWakeTime(r.info.uid,
9575 r.pid, curRealtime);
9576 }
9577 long timeUsed = wtime - r.lastWakeTime;
9578 pw.print(prefix);
9579 pw.print(" ");
9580 pw.print("keep awake over ");
9581 TimeUtils.formatDuration(realtimeSince, pw);
9582 pw.print(" used ");
9583 TimeUtils.formatDuration(timeUsed, pw);
9584 pw.print(" (");
9585 pw.print((timeUsed*100)/realtimeSince);
9586 pw.println("%)");
9587 }
9588 if (r.lastCpuTime != 0) {
9589 long timeUsed = r.curCpuTime - r.lastCpuTime;
9590 pw.print(prefix);
9591 pw.print(" ");
9592 pw.print("run cpu over ");
9593 TimeUtils.formatDuration(uptimeSince, pw);
9594 pw.print(" used ");
9595 TimeUtils.formatDuration(timeUsed, pw);
9596 pw.print(" (");
9597 pw.print((timeUsed*100)/uptimeSince);
9598 pw.println("%)");
9599 }
9600 }
9601 }
9602 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009603 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009604 }
9605
Dianne Hackbornb437e092011-08-05 17:50:29 -07009606 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009607 ArrayList<ProcessRecord> procs;
9608 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009609 if (args != null && args.length > start
9610 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009611 procs = new ArrayList<ProcessRecord>();
9612 int pid = -1;
9613 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009614 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009615 } catch (NumberFormatException e) {
9616
9617 }
9618 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9619 ProcessRecord proc = mLruProcesses.get(i);
9620 if (proc.pid == pid) {
9621 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009622 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009623 procs.add(proc);
9624 }
9625 }
9626 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009627 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009628 return null;
9629 }
9630 } else {
9631 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9632 }
9633 }
9634 return procs;
9635 }
9636
9637 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9638 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009639 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009640 if (procs == null) {
9641 return;
9642 }
9643
9644 long uptime = SystemClock.uptimeMillis();
9645 long realtime = SystemClock.elapsedRealtime();
9646 pw.println("Applications Graphics Acceleration Info:");
9647 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9648
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009649 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9650 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009651 if (r.thread != null) {
9652 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9653 pw.flush();
9654 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009655 TransferPipe tp = new TransferPipe();
9656 try {
9657 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9658 tp.go(fd);
9659 } finally {
9660 tp.kill();
9661 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009662 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009663 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009664 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009665 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009666 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009667 pw.flush();
9668 }
9669 }
9670 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009671 }
9672
Jeff Brown6754ba22011-12-14 20:20:01 -08009673 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9674 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9675 if (procs == null) {
9676 return;
9677 }
9678
9679 pw.println("Applications Database Info:");
9680
9681 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9682 ProcessRecord r = procs.get(i);
9683 if (r.thread != null) {
9684 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9685 pw.flush();
9686 try {
9687 TransferPipe tp = new TransferPipe();
9688 try {
9689 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9690 tp.go(fd);
9691 } finally {
9692 tp.kill();
9693 }
9694 } catch (IOException e) {
9695 pw.println("Failure while dumping the app: " + r);
9696 pw.flush();
9697 } catch (RemoteException e) {
9698 pw.println("Got a RemoteException while dumping the app " + r);
9699 pw.flush();
9700 }
9701 }
9702 }
9703 }
9704
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009705 final static class MemItem {
9706 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009707 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009708 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009709 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009710 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009711
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009712 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009713 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009714 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009715 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009716 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009717 }
9718 }
9719
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009720 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009721 boolean sort) {
9722 if (sort) {
9723 Collections.sort(items, new Comparator<MemItem>() {
9724 @Override
9725 public int compare(MemItem lhs, MemItem rhs) {
9726 if (lhs.pss < rhs.pss) {
9727 return 1;
9728 } else if (lhs.pss > rhs.pss) {
9729 return -1;
9730 }
9731 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009732 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009733 });
9734 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009735
9736 for (int i=0; i<items.size(); i++) {
9737 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009738 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009739 if (mi.subitems != null) {
9740 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9741 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009742 }
9743 }
9744
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009745 // These are in KB.
9746 static final long[] DUMP_MEM_BUCKETS = new long[] {
9747 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9748 120*1024, 160*1024, 200*1024,
9749 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9750 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9751 };
9752
Dianne Hackborn672342c2011-11-29 11:29:02 -08009753 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9754 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009755 int start = label.lastIndexOf('.');
9756 if (start >= 0) start++;
9757 else start = 0;
9758 int end = label.length();
9759 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9760 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9761 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9762 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009763 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009764 out.append(label, start, end);
9765 return;
9766 }
9767 }
9768 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009769 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009770 out.append(label, start, end);
9771 }
9772
9773 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9774 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9775 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9776 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9777 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9778 };
9779 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9780 "System", "Persistent", "Foreground",
9781 "Visible", "Perceptible", "Heavy Weight",
9782 "Backup", "A Services", "Home", "Previous",
9783 "B Services", "Background"
9784 };
9785
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009786 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009787 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009788 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009789 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009790 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009791
9792 int opti = 0;
9793 while (opti < args.length) {
9794 String opt = args[opti];
9795 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9796 break;
9797 }
9798 opti++;
9799 if ("-a".equals(opt)) {
9800 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009801 } else if ("--oom".equals(opt)) {
9802 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009803 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009804 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009805 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009806 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009807 pw.println("If [process] is specified it can be the name or ");
9808 pw.println("pid of a specific process to dump.");
9809 return;
9810 } else {
9811 pw.println("Unknown argument: " + opt + "; use -h for help");
9812 }
9813 }
9814
9815 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009816 if (procs == null) {
9817 return;
9818 }
9819
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009820 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009821 long uptime = SystemClock.uptimeMillis();
9822 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009823
9824 if (procs.size() == 1 || isCheckinRequest) {
9825 dumpAll = true;
9826 }
9827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009828 if (isCheckinRequest) {
9829 // short checkin version
9830 pw.println(uptime + "," + realtime);
9831 pw.flush();
9832 } else {
9833 pw.println("Applications Memory Usage (kB):");
9834 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9835 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009836
Dianne Hackbornb437e092011-08-05 17:50:29 -07009837 String[] innerArgs = new String[args.length-opti];
9838 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9839
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009840 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9841 long nativePss=0, dalvikPss=0, otherPss=0;
9842 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9843
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009844 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9845 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9846 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009847
9848 long totalPss = 0;
9849
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009850 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9851 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009852 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009853 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009854 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9855 pw.flush();
9856 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009857 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009858 if (dumpAll) {
9859 try {
9860 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9861 } catch (RemoteException e) {
9862 if (!isCheckinRequest) {
9863 pw.println("Got RemoteException!");
9864 pw.flush();
9865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009866 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009867 } else {
9868 mi = new Debug.MemoryInfo();
9869 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009871
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009872 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009873 long myTotalPss = mi.getTotalPss();
9874 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009875 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009876 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009877 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009878
9879 nativePss += mi.nativePss;
9880 dalvikPss += mi.dalvikPss;
9881 otherPss += mi.otherPss;
9882 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9883 long mem = mi.getOtherPss(j);
9884 miscPss[j] += mem;
9885 otherPss -= mem;
9886 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009887
9888 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009889 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9890 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009891 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009892 if (oomProcs[oomIndex] == null) {
9893 oomProcs[oomIndex] = new ArrayList<MemItem>();
9894 }
9895 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009896 break;
9897 }
9898 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009900 }
9901 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009902
9903 if (!isCheckinRequest && procs.size() > 1) {
9904 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9905
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009906 catMems.add(new MemItem("Native", "Native", nativePss, -1));
9907 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
9908 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009909 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009910 String label = Debug.MemoryInfo.getOtherLabel(j);
9911 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009912 }
9913
Dianne Hackbornb437e092011-08-05 17:50:29 -07009914 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
9915 for (int j=0; j<oomPss.length; j++) {
9916 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009917 String label = DUMP_MEM_OOM_LABEL[j];
9918 MemItem item = new MemItem(label, label, oomPss[j],
9919 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009920 item.subitems = oomProcs[j];
9921 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009922 }
9923 }
9924
Dianne Hackborn672342c2011-11-29 11:29:02 -08009925 if (outTag != null || outStack != null) {
9926 if (outTag != null) {
9927 appendMemBucket(outTag, totalPss, "total", false);
9928 }
9929 if (outStack != null) {
9930 appendMemBucket(outStack, totalPss, "total", true);
9931 }
9932 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009933 for (int i=0; i<oomMems.size(); i++) {
9934 MemItem miCat = oomMems.get(i);
9935 if (miCat.subitems == null || miCat.subitems.size() < 1) {
9936 continue;
9937 }
9938 if (miCat.id < ProcessList.SERVICE_ADJ
9939 || miCat.id == ProcessList.HOME_APP_ADJ
9940 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009941 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9942 outTag.append(" / ");
9943 }
9944 if (outStack != null) {
9945 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9946 if (firstLine) {
9947 outStack.append(":");
9948 firstLine = false;
9949 }
9950 outStack.append("\n\t at ");
9951 } else {
9952 outStack.append("$");
9953 }
9954 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009955 for (int j=0; j<miCat.subitems.size(); j++) {
9956 MemItem mi = miCat.subitems.get(j);
9957 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009958 if (outTag != null) {
9959 outTag.append(" ");
9960 }
9961 if (outStack != null) {
9962 outStack.append("$");
9963 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009964 }
Dianne Hackborn672342c2011-11-29 11:29:02 -08009965 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
9966 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
9967 }
9968 if (outStack != null) {
9969 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
9970 }
9971 }
9972 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
9973 outStack.append("(");
9974 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
9975 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
9976 outStack.append(DUMP_MEM_OOM_LABEL[k]);
9977 outStack.append(":");
9978 outStack.append(DUMP_MEM_OOM_ADJ[k]);
9979 }
9980 }
9981 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009982 }
9983 }
9984 }
9985 }
9986
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009987 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -07009988 pw.println();
9989 pw.println("Total PSS by process:");
9990 dumpMemItems(pw, " ", procMems, true);
9991 pw.println();
9992 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009993 pw.println("Total PSS by OOM adjustment:");
9994 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009995 if (!oomOnly) {
9996 PrintWriter out = categoryPw != null ? categoryPw : pw;
9997 out.println();
9998 out.println("Total PSS by category:");
9999 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010000 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010001 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010002 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010004 }
10005
10006 /**
10007 * Searches array of arguments for the specified string
10008 * @param args array of argument strings
10009 * @param value value to search for
10010 * @return true if the value is contained in the array
10011 */
10012 private static boolean scanArgs(String[] args, String value) {
10013 if (args != null) {
10014 for (String arg : args) {
10015 if (value.equals(arg)) {
10016 return true;
10017 }
10018 }
10019 }
10020 return false;
10021 }
10022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010023 private final void killServicesLocked(ProcessRecord app,
10024 boolean allowRestart) {
10025 // Report disconnected services.
10026 if (false) {
10027 // XXX we are letting the client link to the service for
10028 // death notifications.
10029 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010030 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010031 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010032 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010033 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010034 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 = r.connections.values().iterator();
10036 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010037 ArrayList<ConnectionRecord> cl = jt.next();
10038 for (int i=0; i<cl.size(); i++) {
10039 ConnectionRecord c = cl.get(i);
10040 if (c.binding.client != app) {
10041 try {
10042 //c.conn.connected(r.className, null);
10043 } catch (Exception e) {
10044 // todo: this should be asynchronous!
10045 Slog.w(TAG, "Exception thrown disconnected servce "
10046 + r.shortName
10047 + " from app " + app.processName, e);
10048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010049 }
10050 }
10051 }
10052 }
10053 }
10054 }
10055 }
10056
10057 // Clean up any connections this application has to other services.
10058 if (app.connections.size() > 0) {
10059 Iterator<ConnectionRecord> it = app.connections.iterator();
10060 while (it.hasNext()) {
10061 ConnectionRecord r = it.next();
10062 removeConnectionLocked(r, app, null);
10063 }
10064 }
10065 app.connections.clear();
10066
10067 if (app.services.size() != 0) {
10068 // Any services running in the application need to be placed
10069 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010070 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010071 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010072 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010073 synchronized (sr.stats.getBatteryStats()) {
10074 sr.stats.stopLaunchedLocked();
10075 }
10076 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010077 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010078 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010079 if (mStoppingServices.remove(sr)) {
10080 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10081 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010082
10083 boolean hasClients = sr.bindings.size() > 0;
10084 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010085 Iterator<IntentBindRecord> bindings
10086 = sr.bindings.values().iterator();
10087 while (bindings.hasNext()) {
10088 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010089 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010090 + ": shouldUnbind=" + b.hasBound);
10091 b.binder = null;
10092 b.requested = b.received = b.hasBound = false;
10093 }
10094 }
10095
Dianne Hackborn070783f2010-12-29 16:46:28 -080010096 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10097 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010098 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010099 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010100 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010101 sr.crashCount, sr.shortName, app.pid);
10102 bringDownServiceLocked(sr, true);
10103 } else if (!allowRestart) {
10104 bringDownServiceLocked(sr, true);
10105 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010106 boolean canceled = scheduleServiceRestartLocked(sr, true);
10107
10108 // Should the service remain running? Note that in the
10109 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010110 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010111 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10112 if (sr.pendingStarts.size() == 0) {
10113 sr.startRequested = false;
10114 if (!hasClients) {
10115 // Whoops, no reason to restart!
10116 bringDownServiceLocked(sr, true);
10117 }
10118 }
10119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010120 }
10121 }
10122
10123 if (!allowRestart) {
10124 app.services.clear();
10125 }
10126 }
10127
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010128 // Make sure we have no more records on the stopping list.
10129 int i = mStoppingServices.size();
10130 while (i > 0) {
10131 i--;
10132 ServiceRecord sr = mStoppingServices.get(i);
10133 if (sr.app == app) {
10134 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010135 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010136 }
10137 }
10138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010139 app.executingServices.clear();
10140 }
10141
10142 private final void removeDyingProviderLocked(ProcessRecord proc,
10143 ContentProviderRecord cpr) {
10144 synchronized (cpr) {
10145 cpr.launchingApp = null;
10146 cpr.notifyAll();
10147 }
10148
Amith Yamasani742a6712011-05-04 14:49:28 -070010149 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010150 String names[] = cpr.info.authority.split(";");
10151 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010152 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010153 }
10154
10155 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10156 while (cit.hasNext()) {
10157 ProcessRecord capp = cit.next();
10158 if (!capp.persistent && capp.thread != null
10159 && capp.pid != 0
10160 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010161 Slog.i(TAG, "Kill " + capp.processName
10162 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010163 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010164 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010165 capp.processName, capp.setAdj, "dying provider "
10166 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010167 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010168 }
10169 }
10170
10171 mLaunchingProviders.remove(cpr);
10172 }
10173
10174 /**
10175 * Main code for cleaning up a process when it has gone away. This is
10176 * called both as a result of the process dying, or directly when stopping
10177 * a process when running in single process mode.
10178 */
10179 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010180 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010181 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010182 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010183 }
10184
Dianne Hackborn36124872009-10-08 16:22:03 -070010185 mProcessesToGc.remove(app);
10186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010187 // Dismiss any open dialogs.
10188 if (app.crashDialog != null) {
10189 app.crashDialog.dismiss();
10190 app.crashDialog = null;
10191 }
10192 if (app.anrDialog != null) {
10193 app.anrDialog.dismiss();
10194 app.anrDialog = null;
10195 }
10196 if (app.waitDialog != null) {
10197 app.waitDialog.dismiss();
10198 app.waitDialog = null;
10199 }
10200
10201 app.crashing = false;
10202 app.notResponding = false;
10203
10204 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010205 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010206 app.thread = null;
10207 app.forcingToForeground = null;
10208 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010209 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010210 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010211 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010212
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010213 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010214
10215 boolean restart = false;
10216
10217 int NL = mLaunchingProviders.size();
10218
10219 // Remove published content providers.
10220 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010221 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010222 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010223 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010224 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010225 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226
10227 // See if someone is waiting for this provider... in which
10228 // case we don't remove it, but just let it restart.
10229 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010230 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010231 for (; i<NL; i++) {
10232 if (mLaunchingProviders.get(i) == cpr) {
10233 restart = true;
10234 break;
10235 }
10236 }
10237 } else {
10238 i = NL;
10239 }
10240
10241 if (i >= NL) {
10242 removeDyingProviderLocked(app, cpr);
10243 NL = mLaunchingProviders.size();
10244 }
10245 }
10246 app.pubProviders.clear();
10247 }
10248
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010249 // Take care of any launching providers waiting for this process.
10250 if (checkAppInLaunchingProvidersLocked(app, false)) {
10251 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010252 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010254 // Unregister from connected content providers.
10255 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010256 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010257 while (it.hasNext()) {
10258 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10259 cpr.clients.remove(app);
10260 }
10261 app.conProviders.clear();
10262 }
10263
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010264 // At this point there may be remaining entries in mLaunchingProviders
10265 // where we were the only one waiting, so they are no longer of use.
10266 // Look for these and clean up if found.
10267 // XXX Commented out for now. Trying to figure out a way to reproduce
10268 // the actual situation to identify what is actually going on.
10269 if (false) {
10270 for (int i=0; i<NL; i++) {
10271 ContentProviderRecord cpr = (ContentProviderRecord)
10272 mLaunchingProviders.get(i);
10273 if (cpr.clients.size() <= 0 && cpr.externals <= 0) {
10274 synchronized (cpr) {
10275 cpr.launchingApp = null;
10276 cpr.notifyAll();
10277 }
10278 }
10279 }
10280 }
10281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010282 skipCurrentReceiverLocked(app);
10283
10284 // Unregister any receivers.
10285 if (app.receivers.size() > 0) {
10286 Iterator<ReceiverList> it = app.receivers.iterator();
10287 while (it.hasNext()) {
10288 removeReceiverLocked(it.next());
10289 }
10290 app.receivers.clear();
10291 }
10292
Christopher Tate181fafa2009-05-14 11:12:14 -070010293 // If the app is undergoing backup, tell the backup manager about it
10294 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010295 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010296 try {
10297 IBackupManager bm = IBackupManager.Stub.asInterface(
10298 ServiceManager.getService(Context.BACKUP_SERVICE));
10299 bm.agentDisconnected(app.info.packageName);
10300 } catch (RemoteException e) {
10301 // can't happen; backup manager is local
10302 }
10303 }
10304
Jeff Sharkey287bd832011-05-28 19:36:26 -070010305 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010307 // If the caller is restarting this app, then leave it in its
10308 // current lists and let the caller take care of it.
10309 if (restarting) {
10310 return;
10311 }
10312
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010313 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010314 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010315 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010316 mProcessNames.remove(app.processName, app.uid);
10317 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010318 if (mHeavyWeightProcess == app) {
10319 mHeavyWeightProcess = null;
10320 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010322 } else if (!app.removed) {
10323 // This app is persistent, so we need to keep its record around.
10324 // If it is not already on the pending app list, add it there
10325 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010326 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10327 mPersistentStartingProcesses.add(app);
10328 restart = true;
10329 }
10330 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010331 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10332 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 mProcessesOnHold.remove(app);
10334
The Android Open Source Project4df24232009-03-05 14:34:35 -080010335 if (app == mHomeProcess) {
10336 mHomeProcess = null;
10337 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010338 if (app == mPreviousProcess) {
10339 mPreviousProcess = null;
10340 }
10341
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010342 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010343 // We have components that still need to be running in the
10344 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010345 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010346 startProcessLocked(app, "restart", app.processName);
10347 } else if (app.pid > 0 && app.pid != MY_PID) {
10348 // Goodbye!
10349 synchronized (mPidsSelfLocked) {
10350 mPidsSelfLocked.remove(app.pid);
10351 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10352 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010353 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010354 }
10355 }
10356
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010357 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10358 // Look through the content providers we are waiting to have launched,
10359 // and if any run in this process then either schedule a restart of
10360 // the process or kill the client waiting for it if this process has
10361 // gone bad.
10362 int NL = mLaunchingProviders.size();
10363 boolean restart = false;
10364 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010365 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010366 if (cpr.launchingApp == app) {
10367 if (!alwaysBad && !app.bad) {
10368 restart = true;
10369 } else {
10370 removeDyingProviderLocked(app, cpr);
10371 NL = mLaunchingProviders.size();
10372 }
10373 }
10374 }
10375 return restart;
10376 }
10377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010378 // =========================================================
10379 // SERVICES
10380 // =========================================================
10381
10382 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10383 ActivityManager.RunningServiceInfo info =
10384 new ActivityManager.RunningServiceInfo();
10385 info.service = r.name;
10386 if (r.app != null) {
10387 info.pid = r.app.pid;
10388 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010389 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010390 info.process = r.processName;
10391 info.foreground = r.isForeground;
10392 info.activeSince = r.createTime;
10393 info.started = r.startRequested;
10394 info.clientCount = r.connections.size();
10395 info.crashCount = r.crashCount;
10396 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010397 if (r.isForeground) {
10398 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10399 }
10400 if (r.startRequested) {
10401 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10402 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010403 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010404 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10405 }
10406 if (r.app != null && r.app.persistent) {
10407 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10408 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010409
10410 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10411 for (int i=0; i<connl.size(); i++) {
10412 ConnectionRecord conn = connl.get(i);
10413 if (conn.clientLabel != 0) {
10414 info.clientPackage = conn.binding.client.info.packageName;
10415 info.clientLabel = conn.clientLabel;
10416 return info;
10417 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010418 }
10419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010420 return info;
10421 }
10422
10423 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10424 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010425 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010426 synchronized (this) {
10427 ArrayList<ActivityManager.RunningServiceInfo> res
10428 = new ArrayList<ActivityManager.RunningServiceInfo>();
10429
Amith Yamasani742a6712011-05-04 14:49:28 -070010430 int userId = UserId.getUserId(Binder.getCallingUid());
10431 if (mServiceMap.getAllServices(userId).size() > 0) {
10432 Iterator<ServiceRecord> it
10433 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010434 while (it.hasNext() && res.size() < maxNum) {
10435 res.add(makeRunningServiceInfoLocked(it.next()));
10436 }
10437 }
10438
10439 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10440 ServiceRecord r = mRestartingServices.get(i);
10441 ActivityManager.RunningServiceInfo info =
10442 makeRunningServiceInfoLocked(r);
10443 info.restarting = r.nextRestartTime;
10444 res.add(info);
10445 }
10446
10447 return res;
10448 }
10449 }
10450
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010451 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010452 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010453 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010454 int userId = UserId.getUserId(Binder.getCallingUid());
10455 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010456 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010457 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10458 for (int i=0; i<conn.size(); i++) {
10459 if (conn.get(i).clientIntent != null) {
10460 return conn.get(i).clientIntent;
10461 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010462 }
10463 }
10464 }
10465 }
10466 return null;
10467 }
10468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010469 private final ServiceRecord findServiceLocked(ComponentName name,
10470 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010471 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472 return r == token ? r : null;
10473 }
10474
10475 private final class ServiceLookupResult {
10476 final ServiceRecord record;
10477 final String permission;
10478
10479 ServiceLookupResult(ServiceRecord _record, String _permission) {
10480 record = _record;
10481 permission = _permission;
10482 }
10483 };
10484
10485 private ServiceLookupResult findServiceLocked(Intent service,
10486 String resolvedType) {
10487 ServiceRecord r = null;
10488 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010489 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010490 }
10491 if (r == null) {
10492 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010493 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 }
10495
10496 if (r == null) {
10497 try {
10498 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010499 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010500 service, resolvedType, 0);
10501 ServiceInfo sInfo =
10502 rInfo != null ? rInfo.serviceInfo : null;
10503 if (sInfo == null) {
10504 return null;
10505 }
10506
10507 ComponentName name = new ComponentName(
10508 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010509 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010510 } catch (RemoteException ex) {
10511 // pm is in same process, this will never happen.
10512 }
10513 }
10514 if (r != null) {
10515 int callingPid = Binder.getCallingPid();
10516 int callingUid = Binder.getCallingUid();
10517 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010518 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010519 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010520 if (!r.exported) {
10521 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10522 + " from pid=" + callingPid
10523 + ", uid=" + callingUid
10524 + " that is not exported from uid " + r.appInfo.uid);
10525 return new ServiceLookupResult(null, "not exported from uid "
10526 + r.appInfo.uid);
10527 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010528 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 + " from pid=" + callingPid
10530 + ", uid=" + callingUid
10531 + " requires " + r.permission);
10532 return new ServiceLookupResult(null, r.permission);
10533 }
10534 return new ServiceLookupResult(r, null);
10535 }
10536 return null;
10537 }
10538
10539 private class ServiceRestarter implements Runnable {
10540 private ServiceRecord mService;
10541
10542 void setService(ServiceRecord service) {
10543 mService = service;
10544 }
10545
10546 public void run() {
10547 synchronized(ActivityManagerService.this) {
10548 performServiceRestartLocked(mService);
10549 }
10550 }
10551 }
10552
10553 private ServiceLookupResult retrieveServiceLocked(Intent service,
10554 String resolvedType, int callingPid, int callingUid) {
10555 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010556 if (DEBUG_SERVICE)
10557 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
10558 + " origCallingUid=" + callingUid);
10559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010560 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010561 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010563 if (r == null) {
10564 Intent.FilterComparison filter = new Intent.FilterComparison(service);
10565 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
10566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 if (r == null) {
10568 try {
10569 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010570 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010571 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 ServiceInfo sInfo =
10573 rInfo != null ? rInfo.serviceInfo : null;
10574 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010575 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 ": not found");
10577 return null;
10578 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010579 if (Binder.getOrigCallingUser() > 0) {
10580 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo,
10581 Binder.getOrigCallingUser());
10582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010583 ComponentName name = new ComponentName(
10584 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010585 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010587 Intent.FilterComparison filter = new Intent.FilterComparison(
10588 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 ServiceRestarter res = new ServiceRestarter();
10590 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10591 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10592 synchronized (stats) {
10593 ss = stats.getServiceStatsLocked(
10594 sInfo.applicationInfo.uid, sInfo.packageName,
10595 sInfo.name);
10596 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010597 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010599 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10600 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601
10602 // Make sure this component isn't in the pending list.
10603 int N = mPendingServices.size();
10604 for (int i=0; i<N; i++) {
10605 ServiceRecord pr = mPendingServices.get(i);
10606 if (pr.name.equals(name)) {
10607 mPendingServices.remove(i);
10608 i--;
10609 N--;
10610 }
10611 }
10612 }
10613 } catch (RemoteException ex) {
10614 // pm is in same process, this will never happen.
10615 }
10616 }
10617 if (r != null) {
10618 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010619 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010620 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010621 if (!r.exported) {
10622 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10623 + " from pid=" + callingPid
10624 + ", uid=" + callingUid
10625 + " that is not exported from uid " + r.appInfo.uid);
10626 return new ServiceLookupResult(null, "not exported from uid "
10627 + r.appInfo.uid);
10628 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010629 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010630 + " from pid=" + callingPid
10631 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 + " requires " + r.permission);
10633 return new ServiceLookupResult(null, r.permission);
10634 }
10635 return new ServiceLookupResult(r, null);
10636 }
10637 return null;
10638 }
10639
Dianne Hackborn287952c2010-09-22 22:34:31 -070010640 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10641 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10642 + why + " of " + r + " in app " + r.app);
10643 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10644 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010645 long now = SystemClock.uptimeMillis();
10646 if (r.executeNesting == 0 && r.app != null) {
10647 if (r.app.executingServices.size() == 0) {
10648 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10649 msg.obj = r.app;
10650 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10651 }
10652 r.app.executingServices.add(r);
10653 }
10654 r.executeNesting++;
10655 r.executingStart = now;
10656 }
10657
10658 private final void sendServiceArgsLocked(ServiceRecord r,
10659 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010660 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010661 if (N == 0) {
10662 return;
10663 }
10664
Dianne Hackborn39792d22010-08-19 18:01:52 -070010665 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010667 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010668 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10669 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010670 if (si.intent == null && N > 1) {
10671 // If somehow we got a dummy null intent in the middle,
10672 // then skip it. DO NOT skip a null intent when it is
10673 // the only one in the list -- this is to support the
10674 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010675 continue;
10676 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010677 si.deliveredTime = SystemClock.uptimeMillis();
10678 r.deliveredStarts.add(si);
10679 si.deliveryCount++;
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010680 if (si.targetPermissionUid >= 0 && si.intent != null) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010681 grantUriPermissionUncheckedFromIntentLocked(si.targetPermissionUid,
Dianne Hackborn7e269642010-08-25 19:50:20 -070010682 r.packageName, si.intent, si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010683 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010684 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010685 if (!oomAdjusted) {
10686 oomAdjusted = true;
10687 updateOomAdjLocked(r.app);
10688 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010689 int flags = 0;
10690 if (si.deliveryCount > 0) {
10691 flags |= Service.START_FLAG_RETRY;
10692 }
10693 if (si.doneExecutingCount > 0) {
10694 flags |= Service.START_FLAG_REDELIVERY;
10695 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010696 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010697 } catch (RemoteException e) {
10698 // Remote process gone... we'll let the normal cleanup take
10699 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010700 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010701 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010702 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010703 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010704 break;
10705 }
10706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 }
10708
10709 private final boolean requestServiceBindingLocked(ServiceRecord r,
10710 IntentBindRecord i, boolean rebind) {
10711 if (r.app == null || r.app.thread == null) {
10712 // If service is not currently running, can't yet bind.
10713 return false;
10714 }
10715 if ((!i.requested || rebind) && i.apps.size() > 0) {
10716 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010717 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010718 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10719 if (!rebind) {
10720 i.requested = true;
10721 }
10722 i.hasBound = true;
10723 i.doRebind = false;
10724 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010725 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 return false;
10727 }
10728 }
10729 return true;
10730 }
10731
10732 private final void requestServiceBindingsLocked(ServiceRecord r) {
10733 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10734 while (bindings.hasNext()) {
10735 IntentBindRecord i = bindings.next();
10736 if (!requestServiceBindingLocked(r, i, false)) {
10737 break;
10738 }
10739 }
10740 }
10741
10742 private final void realStartServiceLocked(ServiceRecord r,
10743 ProcessRecord app) throws RemoteException {
10744 if (app.thread == null) {
10745 throw new RemoteException();
10746 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010747 if (DEBUG_MU)
10748 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010749 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010751 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010752
10753 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010754 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010755 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756
10757 boolean created = false;
10758 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010759 mStringBuilder.setLength(0);
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010760 r.intent.getIntent().toShortString(mStringBuilder, true, false, true);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010761 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010763 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010764 synchronized (r.stats.getBatteryStats()) {
10765 r.stats.startLaunchedLocked();
10766 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010767 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010768 app.thread.scheduleCreateService(r, r.serviceInfo,
10769 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010770 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 created = true;
10772 } finally {
10773 if (!created) {
10774 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010775 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 }
10777 }
10778
10779 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010780
10781 // If the service is in the started state, and there are no
10782 // pending arguments, then fake up one so its onStartCommand() will
10783 // be called.
10784 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010785 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
10786 null, -1));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010787 }
10788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 sendServiceArgsLocked(r, true);
10790 }
10791
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010792 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10793 boolean allowCancel) {
10794 boolean canceled = false;
10795
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010796 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010797 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010798 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010799
Dianne Hackborn070783f2010-12-29 16:46:28 -080010800 if ((r.serviceInfo.applicationInfo.flags
10801 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10802 minDuration /= 4;
10803 }
10804
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010805 // Any delivered but not yet finished starts should be put back
10806 // on the pending list.
10807 final int N = r.deliveredStarts.size();
10808 if (N > 0) {
10809 for (int i=N-1; i>=0; i--) {
10810 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010811 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010812 if (si.intent == null) {
10813 // We'll generate this again if needed.
10814 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10815 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10816 r.pendingStarts.add(0, si);
10817 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10818 dur *= 2;
10819 if (minDuration < dur) minDuration = dur;
10820 if (resetTime < dur) resetTime = dur;
10821 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010822 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010823 + r.name);
10824 canceled = true;
10825 }
10826 }
10827 r.deliveredStarts.clear();
10828 }
10829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010830 r.totalRestartCount++;
10831 if (r.restartDelay == 0) {
10832 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010833 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834 } else {
10835 // If it has been a "reasonably long time" since the service
10836 // was started, then reset our restart duration back to
10837 // the beginning, so we don't infinitely increase the duration
10838 // on a service that just occasionally gets killed (which is
10839 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010840 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010841 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010842 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010843 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010844 if ((r.serviceInfo.applicationInfo.flags
10845 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10846 // Services in peristent processes will restart much more
10847 // quickly, since they are pretty important. (Think SystemUI).
10848 r.restartDelay += minDuration/2;
10849 } else {
10850 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10851 if (r.restartDelay < minDuration) {
10852 r.restartDelay = minDuration;
10853 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855 }
10856 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010857
10858 r.nextRestartTime = now + r.restartDelay;
10859
10860 // Make sure that we don't end up restarting a bunch of services
10861 // all at the same time.
10862 boolean repeat;
10863 do {
10864 repeat = false;
10865 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10866 ServiceRecord r2 = mRestartingServices.get(i);
10867 if (r2 != r && r.nextRestartTime
10868 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10869 && r.nextRestartTime
10870 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10871 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10872 r.restartDelay = r.nextRestartTime - now;
10873 repeat = true;
10874 break;
10875 }
10876 }
10877 } while (repeat);
10878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010879 if (!mRestartingServices.contains(r)) {
10880 mRestartingServices.add(r);
10881 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010882
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010883 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010885 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010886 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010888 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010889 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010890 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 r.shortName, r.restartDelay);
10892
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010893 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 }
10895
10896 final void performServiceRestartLocked(ServiceRecord r) {
10897 if (!mRestartingServices.contains(r)) {
10898 return;
10899 }
10900 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10901 }
10902
10903 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10904 if (r.restartDelay == 0) {
10905 return false;
10906 }
10907 r.resetRestartCounter();
10908 mRestartingServices.remove(r);
10909 mHandler.removeCallbacks(r.restarter);
10910 return true;
10911 }
10912
10913 private final boolean bringUpServiceLocked(ServiceRecord r,
10914 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010915 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 //r.dump(" ");
10917
Dianne Hackborn36124872009-10-08 16:22:03 -070010918 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010919 sendServiceArgsLocked(r, false);
10920 return true;
10921 }
10922
10923 if (!whileRestarting && r.restartDelay > 0) {
10924 // If waiting for a restart, then do nothing.
10925 return true;
10926 }
10927
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010928 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010929
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010930 // We are now bringing the service up, so no longer in the
10931 // restarting state.
10932 mRestartingServices.remove(r);
10933
Dianne Hackborne7f97212011-02-24 14:40:20 -080010934 // Service is now being launched, its package can't be stopped.
10935 try {
10936 AppGlobals.getPackageManager().setPackageStoppedState(
10937 r.packageName, false);
10938 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010939 } catch (IllegalArgumentException e) {
10940 Slog.w(TAG, "Failed trying to unstop package "
10941 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010942 }
10943
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010944 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010945 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010946 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010947
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010948 if (!isolated) {
10949 app = getProcessRecordLocked(appName, r.appInfo.uid);
10950 if (DEBUG_MU)
10951 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
10952 if (app != null && app.thread != null) {
10953 try {
10954 app.addPackage(r.appInfo.packageName);
10955 realStartServiceLocked(r, app);
10956 return true;
10957 } catch (RemoteException e) {
10958 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
10959 }
10960
10961 // If a dead object exception was thrown -- fall through to
10962 // restart the application.
10963 }
10964 } else {
10965 // If this service runs in an isolated process, then each time
10966 // we call startProcessLocked() we will get a new isolated
10967 // process, starting another process if we are currently waiting
10968 // for a previous process to come up. To deal with this, we store
10969 // in the service any current isolated process it is running in or
10970 // waiting to have come up.
10971 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010972 }
10973
Dianne Hackborn36124872009-10-08 16:22:03 -070010974 // Not running -- get it started, and enqueue this service record
10975 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010976 if (app == null) {
10977 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
10978 "service", r.name, false, isolated)) == null) {
10979 Slog.w(TAG, "Unable to launch app "
10980 + r.appInfo.packageName + "/"
10981 + r.appInfo.uid + " for service "
10982 + r.intent.getIntent() + ": process is bad");
10983 bringDownServiceLocked(r, true);
10984 return false;
10985 }
10986 if (isolated) {
10987 r.isolatedProc = app;
10988 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010989 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010992 mPendingServices.add(r);
10993 }
Dianne Hackborn36124872009-10-08 16:22:03 -070010994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010995 return true;
10996 }
10997
10998 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010999 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011000 //r.dump(" ");
11001
11002 // Does it still need to run?
11003 if (!force && r.startRequested) {
11004 return;
11005 }
11006 if (r.connections.size() > 0) {
11007 if (!force) {
11008 // XXX should probably keep a count of the number of auto-create
11009 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011010 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011012 ArrayList<ConnectionRecord> cr = it.next();
11013 for (int i=0; i<cr.size(); i++) {
11014 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11015 return;
11016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017 }
11018 }
11019 }
11020
11021 // Report to all of the connections that the service is no longer
11022 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011023 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011024 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011025 ArrayList<ConnectionRecord> c = it.next();
11026 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011027 ConnectionRecord cr = c.get(i);
11028 // There is still a connection to the service that is
11029 // being brought down. Mark it as dead.
11030 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011031 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011032 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011033 } catch (Exception e) {
11034 Slog.w(TAG, "Failure disconnecting service " + r.name +
11035 " to connection " + c.get(i).conn.asBinder() +
11036 " (in " + c.get(i).binding.client.processName + ")", e);
11037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011038 }
11039 }
11040 }
11041
11042 // Tell the service that it has been unbound.
11043 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11044 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11045 while (it.hasNext()) {
11046 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011047 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011048 + ": hasBound=" + ibr.hasBound);
11049 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11050 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011051 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 updateOomAdjLocked(r.app);
11053 ibr.hasBound = false;
11054 r.app.thread.scheduleUnbindService(r,
11055 ibr.intent.getIntent());
11056 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011057 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011058 + r.shortName, e);
11059 serviceDoneExecutingLocked(r, true);
11060 }
11061 }
11062 }
11063 }
11064
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011065 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011066 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011067 System.identityHashCode(r), r.shortName,
11068 (r.app != null) ? r.app.pid : -1);
11069
Amith Yamasani742a6712011-05-04 14:49:28 -070011070 mServiceMap.removeServiceByName(r.name, r.userId);
11071 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 r.totalRestartCount = 0;
11073 unscheduleServiceRestartLocked(r);
11074
11075 // Also make sure it is not on the pending list.
11076 int N = mPendingServices.size();
11077 for (int i=0; i<N; i++) {
11078 if (mPendingServices.get(i) == r) {
11079 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011080 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 i--;
11082 N--;
11083 }
11084 }
11085
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011086 r.cancelNotification();
11087 r.isForeground = false;
11088 r.foregroundId = 0;
11089 r.foregroundNoti = null;
11090
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011091 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011092 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011093 r.pendingStarts.clear();
11094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 if (r.app != null) {
11096 synchronized (r.stats.getBatteryStats()) {
11097 r.stats.stopLaunchedLocked();
11098 }
11099 r.app.services.remove(r);
11100 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011102 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 mStoppingServices.add(r);
11104 updateOomAdjLocked(r.app);
11105 r.app.thread.scheduleStopService(r);
11106 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011107 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011108 + r.shortName, e);
11109 serviceDoneExecutingLocked(r, true);
11110 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011111 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011112 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011113 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011114 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011115 }
11116 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011117 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011118 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011119 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011120
11121 if (r.bindings.size() > 0) {
11122 r.bindings.clear();
11123 }
11124
11125 if (r.restarter instanceof ServiceRestarter) {
11126 ((ServiceRestarter)r.restarter).setService(null);
11127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 }
11129
11130 ComponentName startServiceLocked(IApplicationThread caller,
11131 Intent service, String resolvedType,
11132 int callingPid, int callingUid) {
11133 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011134 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011135 + " type=" + resolvedType + " args=" + service.getExtras());
11136
11137 if (caller != null) {
11138 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11139 if (callerApp == null) {
11140 throw new SecurityException(
11141 "Unable to find app for caller " + caller
11142 + " (pid=" + Binder.getCallingPid()
11143 + ") when starting service " + service);
11144 }
11145 }
11146
11147 ServiceLookupResult res =
11148 retrieveServiceLocked(service, resolvedType,
11149 callingPid, callingUid);
11150 if (res == null) {
11151 return null;
11152 }
11153 if (res.record == null) {
11154 return new ComponentName("!", res.permission != null
11155 ? res.permission : "private to package");
11156 }
11157 ServiceRecord r = res.record;
Dianne Hackborn39792d22010-08-19 18:01:52 -070011158 int targetPermissionUid = checkGrantUriPermissionFromIntentLocked(
11159 callingUid, r.packageName, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011160 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011161 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011162 }
11163 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011164 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011165 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn39792d22010-08-19 18:01:52 -070011166 service, targetPermissionUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 r.lastActivity = SystemClock.uptimeMillis();
11168 synchronized (r.stats.getBatteryStats()) {
11169 r.stats.startRunningLocked();
11170 }
11171 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11172 return new ComponentName("!", "Service process is bad");
11173 }
11174 return r.name;
11175 }
11176 }
11177
11178 public ComponentName startService(IApplicationThread caller, Intent service,
11179 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011180 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011181 // Refuse possible leaked file descriptors
11182 if (service != null && service.hasFileDescriptors() == true) {
11183 throw new IllegalArgumentException("File descriptors passed in Intent");
11184 }
11185
Amith Yamasani742a6712011-05-04 14:49:28 -070011186 if (DEBUG_SERVICE)
11187 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 synchronized(this) {
11189 final int callingPid = Binder.getCallingPid();
11190 final int callingUid = Binder.getCallingUid();
11191 final long origId = Binder.clearCallingIdentity();
11192 ComponentName res = startServiceLocked(caller, service,
11193 resolvedType, callingPid, callingUid);
11194 Binder.restoreCallingIdentity(origId);
11195 return res;
11196 }
11197 }
11198
11199 ComponentName startServiceInPackage(int uid,
11200 Intent service, String resolvedType) {
11201 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011202 if (DEBUG_SERVICE)
11203 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 final long origId = Binder.clearCallingIdentity();
11205 ComponentName res = startServiceLocked(null, service,
11206 resolvedType, -1, uid);
11207 Binder.restoreCallingIdentity(origId);
11208 return res;
11209 }
11210 }
11211
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011212 private void stopServiceLocked(ServiceRecord service) {
11213 synchronized (service.stats.getBatteryStats()) {
11214 service.stats.stopRunningLocked();
11215 }
11216 service.startRequested = false;
11217 service.callStart = false;
11218 bringDownServiceLocked(service, false);
11219 }
11220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221 public int stopService(IApplicationThread caller, Intent service,
11222 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011223 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 // Refuse possible leaked file descriptors
11225 if (service != null && service.hasFileDescriptors() == true) {
11226 throw new IllegalArgumentException("File descriptors passed in Intent");
11227 }
11228
11229 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011230 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231 + " type=" + resolvedType);
11232
11233 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11234 if (caller != null && callerApp == null) {
11235 throw new SecurityException(
11236 "Unable to find app for caller " + caller
11237 + " (pid=" + Binder.getCallingPid()
11238 + ") when stopping service " + service);
11239 }
11240
11241 // If this service is active, make sure it is stopped.
11242 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11243 if (r != null) {
11244 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011246 try {
11247 stopServiceLocked(r.record);
11248 } finally {
11249 Binder.restoreCallingIdentity(origId);
11250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 return 1;
11252 }
11253 return -1;
11254 }
11255 }
11256
11257 return 0;
11258 }
11259
11260 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011261 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011262 // Refuse possible leaked file descriptors
11263 if (service != null && service.hasFileDescriptors() == true) {
11264 throw new IllegalArgumentException("File descriptors passed in Intent");
11265 }
11266
11267 IBinder ret = null;
11268
11269 synchronized(this) {
11270 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11271
11272 if (r != null) {
11273 // r.record is null if findServiceLocked() failed the caller permission check
11274 if (r.record == null) {
11275 throw new SecurityException(
11276 "Permission Denial: Accessing service " + r.record.name
11277 + " from pid=" + Binder.getCallingPid()
11278 + ", uid=" + Binder.getCallingUid()
11279 + " requires " + r.permission);
11280 }
11281 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11282 if (ib != null) {
11283 ret = ib.binder;
11284 }
11285 }
11286 }
11287
11288 return ret;
11289 }
11290
11291 public boolean stopServiceToken(ComponentName className, IBinder token,
11292 int startId) {
11293 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011294 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295 + " " + token + " startId=" + startId);
11296 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011297 if (r != null) {
11298 if (startId >= 0) {
11299 // Asked to only stop if done with all work. Note that
11300 // to avoid leaks, we will take this as dropping all
11301 // start items up to and including this one.
11302 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11303 if (si != null) {
11304 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011305 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11306 cur.removeUriPermissionsLocked();
11307 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011308 break;
11309 }
11310 }
11311 }
11312
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011313 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011314 return false;
11315 }
11316
11317 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011318 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011319 + " is last, but have " + r.deliveredStarts.size()
11320 + " remaining args");
11321 }
11322 }
11323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324 synchronized (r.stats.getBatteryStats()) {
11325 r.stats.stopRunningLocked();
11326 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011327 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 }
11329 final long origId = Binder.clearCallingIdentity();
11330 bringDownServiceLocked(r, false);
11331 Binder.restoreCallingIdentity(origId);
11332 return true;
11333 }
11334 }
11335 return false;
11336 }
11337
11338 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011339 int id, Notification notification, boolean removeNotification) {
11340 final long origId = Binder.clearCallingIdentity();
11341 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 synchronized(this) {
11343 ServiceRecord r = findServiceLocked(className, token);
11344 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011345 if (id != 0) {
11346 if (notification == null) {
11347 throw new IllegalArgumentException("null notification");
11348 }
11349 if (r.foregroundId != id) {
11350 r.cancelNotification();
11351 r.foregroundId = id;
11352 }
11353 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11354 r.foregroundNoti = notification;
11355 r.isForeground = true;
11356 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357 if (r.app != null) {
11358 updateServiceForegroundLocked(r.app, true);
11359 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011360 } else {
11361 if (r.isForeground) {
11362 r.isForeground = false;
11363 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011364 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011365 updateServiceForegroundLocked(r.app, true);
11366 }
11367 }
11368 if (removeNotification) {
11369 r.cancelNotification();
11370 r.foregroundId = 0;
11371 r.foregroundNoti = null;
11372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 }
11374 }
11375 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011376 } finally {
11377 Binder.restoreCallingIdentity(origId);
11378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 }
11380
11381 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11382 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011383 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384 if (sr.isForeground) {
11385 anyForeground = true;
11386 break;
11387 }
11388 }
11389 if (anyForeground != proc.foregroundServices) {
11390 proc.foregroundServices = anyForeground;
11391 if (oomAdj) {
11392 updateOomAdjLocked();
11393 }
11394 }
11395 }
11396
11397 public int bindService(IApplicationThread caller, IBinder token,
11398 Intent service, String resolvedType,
11399 IServiceConnection connection, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011400 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 // Refuse possible leaked file descriptors
11402 if (service != null && service.hasFileDescriptors() == true) {
11403 throw new IllegalArgumentException("File descriptors passed in Intent");
11404 }
11405
11406 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011407 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 + " type=" + resolvedType + " conn=" + connection.asBinder()
11409 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011410 if (DEBUG_MU)
11411 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11412 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11414 if (callerApp == null) {
11415 throw new SecurityException(
11416 "Unable to find app for caller " + caller
11417 + " (pid=" + Binder.getCallingPid()
11418 + ") when binding service " + service);
11419 }
11420
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011421 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011423 activity = mMainStack.isInStackLocked(token);
11424 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011425 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 return 0;
11427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 }
11429
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011430 int clientLabel = 0;
11431 PendingIntent clientIntent = null;
11432
11433 if (callerApp.info.uid == Process.SYSTEM_UID) {
11434 // Hacky kind of thing -- allow system stuff to tell us
11435 // what they are, so we can report this elsewhere for
11436 // others to know why certain services are running.
11437 try {
11438 clientIntent = (PendingIntent)service.getParcelableExtra(
11439 Intent.EXTRA_CLIENT_INTENT);
11440 } catch (RuntimeException e) {
11441 }
11442 if (clientIntent != null) {
11443 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11444 if (clientLabel != 0) {
11445 // There are no useful extras in the intent, trash them.
11446 // System code calling with this stuff just needs to know
11447 // this will happen.
11448 service = service.cloneFilter();
11449 }
11450 }
11451 }
11452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 ServiceLookupResult res =
11454 retrieveServiceLocked(service, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -070011455 Binder.getCallingPid(), Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011456 if (res == null) {
11457 return 0;
11458 }
11459 if (res.record == null) {
11460 return -1;
11461 }
11462 ServiceRecord s = res.record;
11463
11464 final long origId = Binder.clearCallingIdentity();
11465
11466 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011467 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011468 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011469 }
11470
11471 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11472 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011473 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474
11475 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011476 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11477 if (clist == null) {
11478 clist = new ArrayList<ConnectionRecord>();
11479 s.connections.put(binder, clist);
11480 }
11481 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 b.connections.add(c);
11483 if (activity != null) {
11484 if (activity.connections == null) {
11485 activity.connections = new HashSet<ConnectionRecord>();
11486 }
11487 activity.connections.add(c);
11488 }
11489 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011490 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11491 b.client.hasAboveClient = true;
11492 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011493 clist = mServiceConnections.get(binder);
11494 if (clist == null) {
11495 clist = new ArrayList<ConnectionRecord>();
11496 mServiceConnections.put(binder, clist);
11497 }
11498 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499
11500 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11501 s.lastActivity = SystemClock.uptimeMillis();
11502 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11503 return 0;
11504 }
11505 }
11506
11507 if (s.app != null) {
11508 // This could have made the service more important.
11509 updateOomAdjLocked(s.app);
11510 }
11511
Joe Onorato8a9b2202010-02-26 18:56:32 -080011512 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011513 + ": received=" + b.intent.received
11514 + " apps=" + b.intent.apps.size()
11515 + " doRebind=" + b.intent.doRebind);
11516
11517 if (s.app != null && b.intent.received) {
11518 // Service is already running, so we can immediately
11519 // publish the connection.
11520 try {
11521 c.conn.connected(s.name, b.intent.binder);
11522 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011523 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 + " to connection " + c.conn.asBinder()
11525 + " (in " + c.binding.client.processName + ")", e);
11526 }
11527
11528 // If this is the first app connected back to this binding,
11529 // and the service had previously asked to be told when
11530 // rebound, then do so.
11531 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11532 requestServiceBindingLocked(s, b.intent, true);
11533 }
11534 } else if (!b.intent.requested) {
11535 requestServiceBindingLocked(s, b.intent, false);
11536 }
11537
11538 Binder.restoreCallingIdentity(origId);
11539 }
11540
11541 return 1;
11542 }
11543
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011544 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011545 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 IBinder binder = c.conn.asBinder();
11547 AppBindRecord b = c.binding;
11548 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011549 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11550 if (clist != null) {
11551 clist.remove(c);
11552 if (clist.size() == 0) {
11553 s.connections.remove(binder);
11554 }
11555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011556 b.connections.remove(c);
11557 if (c.activity != null && c.activity != skipAct) {
11558 if (c.activity.connections != null) {
11559 c.activity.connections.remove(c);
11560 }
11561 }
11562 if (b.client != skipApp) {
11563 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011564 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11565 b.client.updateHasAboveClientLocked();
11566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011567 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011568 clist = mServiceConnections.get(binder);
11569 if (clist != null) {
11570 clist.remove(c);
11571 if (clist.size() == 0) {
11572 mServiceConnections.remove(binder);
11573 }
11574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011575
11576 if (b.connections.size() == 0) {
11577 b.intent.apps.remove(b.client);
11578 }
11579
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011580 if (!c.serviceDead) {
11581 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11582 + ": shouldUnbind=" + b.intent.hasBound);
11583 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11584 && b.intent.hasBound) {
11585 try {
11586 bumpServiceExecutingLocked(s, "unbind");
11587 updateOomAdjLocked(s.app);
11588 b.intent.hasBound = false;
11589 // Assume the client doesn't want to know about a rebind;
11590 // we will deal with that later if it asks for one.
11591 b.intent.doRebind = false;
11592 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11593 } catch (Exception e) {
11594 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11595 serviceDoneExecutingLocked(s, true);
11596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011598
11599 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11600 bringDownServiceLocked(s, false);
11601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 }
11603 }
11604
11605 public boolean unbindService(IServiceConnection connection) {
11606 synchronized (this) {
11607 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011608 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011609 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11610 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011611 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011612 + connection.asBinder());
11613 return false;
11614 }
11615
11616 final long origId = Binder.clearCallingIdentity();
11617
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011618 while (clist.size() > 0) {
11619 ConnectionRecord r = clist.get(0);
11620 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011622 if (r.binding.service.app != null) {
11623 // This could have made the service less important.
11624 updateOomAdjLocked(r.binding.service.app);
11625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626 }
11627
11628 Binder.restoreCallingIdentity(origId);
11629 }
11630
11631 return true;
11632 }
11633
11634 public void publishService(IBinder token, Intent intent, IBinder service) {
11635 // Refuse possible leaked file descriptors
11636 if (intent != null && intent.hasFileDescriptors() == true) {
11637 throw new IllegalArgumentException("File descriptors passed in Intent");
11638 }
11639
11640 synchronized(this) {
11641 if (!(token instanceof ServiceRecord)) {
11642 throw new IllegalArgumentException("Invalid service token");
11643 }
11644 ServiceRecord r = (ServiceRecord)token;
11645
11646 final long origId = Binder.clearCallingIdentity();
11647
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011648 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011649 + " " + intent + ": " + service);
11650 if (r != null) {
11651 Intent.FilterComparison filter
11652 = new Intent.FilterComparison(intent);
11653 IntentBindRecord b = r.bindings.get(filter);
11654 if (b != null && !b.received) {
11655 b.binder = service;
11656 b.requested = true;
11657 b.received = true;
11658 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011659 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011660 = r.connections.values().iterator();
11661 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011662 ArrayList<ConnectionRecord> clist = it.next();
11663 for (int i=0; i<clist.size(); i++) {
11664 ConnectionRecord c = clist.get(i);
11665 if (!filter.equals(c.binding.intent.intent)) {
11666 if (DEBUG_SERVICE) Slog.v(
11667 TAG, "Not publishing to: " + c);
11668 if (DEBUG_SERVICE) Slog.v(
11669 TAG, "Bound intent: " + c.binding.intent.intent);
11670 if (DEBUG_SERVICE) Slog.v(
11671 TAG, "Published intent: " + intent);
11672 continue;
11673 }
11674 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11675 try {
11676 c.conn.connected(r.name, service);
11677 } catch (Exception e) {
11678 Slog.w(TAG, "Failure sending service " + r.name +
11679 " to connection " + c.conn.asBinder() +
11680 " (in " + c.binding.client.processName + ")", e);
11681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011682 }
11683 }
11684 }
11685 }
11686
11687 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11688
11689 Binder.restoreCallingIdentity(origId);
11690 }
11691 }
11692 }
11693
11694 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11695 // Refuse possible leaked file descriptors
11696 if (intent != null && intent.hasFileDescriptors() == true) {
11697 throw new IllegalArgumentException("File descriptors passed in Intent");
11698 }
11699
11700 synchronized(this) {
11701 if (!(token instanceof ServiceRecord)) {
11702 throw new IllegalArgumentException("Invalid service token");
11703 }
11704 ServiceRecord r = (ServiceRecord)token;
11705
11706 final long origId = Binder.clearCallingIdentity();
11707
11708 if (r != null) {
11709 Intent.FilterComparison filter
11710 = new Intent.FilterComparison(intent);
11711 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011712 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 + " at " + b + ": apps="
11714 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011715
11716 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011718 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 // Applications have already bound since the last
11720 // unbind, so just rebind right here.
11721 requestServiceBindingLocked(r, b, true);
11722 } else {
11723 // Note to tell the service the next time there is
11724 // a new client.
11725 b.doRebind = true;
11726 }
11727 }
11728
Per Edelberg78f9fff2010-08-30 20:01:35 +020011729 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730
11731 Binder.restoreCallingIdentity(origId);
11732 }
11733 }
11734 }
11735
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011736 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737 synchronized(this) {
11738 if (!(token instanceof ServiceRecord)) {
11739 throw new IllegalArgumentException("Invalid service token");
11740 }
11741 ServiceRecord r = (ServiceRecord)token;
11742 boolean inStopping = mStoppingServices.contains(token);
11743 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011745 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011746 + " with incorrect token: given " + token
11747 + ", expected " + r);
11748 return;
11749 }
11750
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011751 if (type == 1) {
11752 // This is a call from a service start... take care of
11753 // book-keeping.
11754 r.callStart = true;
11755 switch (res) {
11756 case Service.START_STICKY_COMPATIBILITY:
11757 case Service.START_STICKY: {
11758 // We are done with the associated start arguments.
11759 r.findDeliveredStart(startId, true);
11760 // Don't stop if killed.
11761 r.stopIfKilled = false;
11762 break;
11763 }
11764 case Service.START_NOT_STICKY: {
11765 // We are done with the associated start arguments.
11766 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011767 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011768 // There is no more work, and this service
11769 // doesn't want to hang around if killed.
11770 r.stopIfKilled = true;
11771 }
11772 break;
11773 }
11774 case Service.START_REDELIVER_INTENT: {
11775 // We'll keep this item until they explicitly
11776 // call stop for it, but keep track of the fact
11777 // that it was delivered.
11778 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11779 if (si != null) {
11780 si.deliveryCount = 0;
11781 si.doneExecutingCount++;
11782 // Don't stop if killed.
11783 r.stopIfKilled = true;
11784 }
11785 break;
11786 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011787 case Service.START_TASK_REMOVED_COMPLETE: {
11788 // Special processing for onTaskRemoved(). Don't
11789 // impact normal onStartCommand() processing.
11790 r.findDeliveredStart(startId, true);
11791 break;
11792 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011793 default:
11794 throw new IllegalArgumentException(
11795 "Unknown service start result: " + res);
11796 }
11797 if (res == Service.START_STICKY_COMPATIBILITY) {
11798 r.callStart = false;
11799 }
11800 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011801 if (DEBUG_MU)
11802 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11803 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011804 final long origId = Binder.clearCallingIdentity();
11805 serviceDoneExecutingLocked(r, inStopping);
11806 Binder.restoreCallingIdentity(origId);
11807 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011808 Slog.w(TAG, "Done executing unknown service from pid "
11809 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 }
11811 }
11812 }
11813
11814 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011815 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11816 + ": nesting=" + r.executeNesting
11817 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011818 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011819 r.executeNesting--;
11820 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011821 if (DEBUG_SERVICE) Slog.v(TAG,
11822 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823 r.app.executingServices.remove(r);
11824 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011825 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11826 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11828 }
11829 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011830 if (DEBUG_SERVICE) Slog.v(TAG,
11831 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011833 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 }
11835 updateOomAdjLocked(r.app);
11836 }
11837 }
11838
11839 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011840 String anrMessage = null;
11841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842 synchronized(this) {
11843 if (proc.executingServices.size() == 0 || proc.thread == null) {
11844 return;
11845 }
11846 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11847 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11848 ServiceRecord timeout = null;
11849 long nextTime = 0;
11850 while (it.hasNext()) {
11851 ServiceRecord sr = it.next();
11852 if (sr.executingStart < maxTime) {
11853 timeout = sr;
11854 break;
11855 }
11856 if (sr.executingStart > nextTime) {
11857 nextTime = sr.executingStart;
11858 }
11859 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011860 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011861 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011862 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 } else {
11864 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11865 msg.obj = proc;
11866 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11867 }
11868 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011869
11870 if (anrMessage != null) {
11871 appNotResponding(proc, null, null, anrMessage);
11872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011873 }
11874
11875 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011876 // BACKUP AND RESTORE
11877 // =========================================================
11878
11879 // Cause the target app to be launched if necessary and its backup agent
11880 // instantiated. The backup agent will invoke backupAgentCreated() on the
11881 // activity manager to announce its creation.
11882 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011883 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011884 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11885
11886 synchronized(this) {
11887 // !!! TODO: currently no check here that we're already bound
11888 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11889 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11890 synchronized (stats) {
11891 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11892 }
11893
Dianne Hackborne7f97212011-02-24 14:40:20 -080011894 // Backup agent is now in use, its package can't be stopped.
11895 try {
11896 AppGlobals.getPackageManager().setPackageStoppedState(
11897 app.packageName, false);
11898 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011899 } catch (IllegalArgumentException e) {
11900 Slog.w(TAG, "Failed trying to unstop package "
11901 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011902 }
11903
Christopher Tate181fafa2009-05-14 11:12:14 -070011904 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011905 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11906 ? new ComponentName(app.packageName, app.backupAgentName)
11907 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011908 // startProcessLocked() returns existing proc's record if it's already running
11909 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011910 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011911 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011912 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011913 return false;
11914 }
11915
11916 r.app = proc;
11917 mBackupTarget = r;
11918 mBackupAppName = app.packageName;
11919
Christopher Tate6fa95972009-06-05 18:43:55 -070011920 // Try not to kill the process during backup
11921 updateOomAdjLocked(proc);
11922
Christopher Tate181fafa2009-05-14 11:12:14 -070011923 // If the process is already attached, schedule the creation of the backup agent now.
11924 // If it is not yet live, this will be done when it attaches to the framework.
11925 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011926 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011927 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011928 proc.thread.scheduleCreateBackupAgent(app,
11929 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011930 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011931 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011932 }
11933 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011934 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011935 }
11936 // Invariants: at this point, the target app process exists and the application
11937 // is either already running or in the process of coming up. mBackupTarget and
11938 // mBackupAppName describe the app, so that when it binds back to the AM we
11939 // know that it's scheduled for a backup-agent operation.
11940 }
11941
11942 return true;
11943 }
11944
11945 // A backup agent has just come up
11946 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011947 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011948 + " = " + agent);
11949
11950 synchronized(this) {
11951 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011952 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011953 return;
11954 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011955 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011956
Dianne Hackborn06740692010-09-22 22:46:21 -070011957 long oldIdent = Binder.clearCallingIdentity();
11958 try {
11959 IBackupManager bm = IBackupManager.Stub.asInterface(
11960 ServiceManager.getService(Context.BACKUP_SERVICE));
11961 bm.agentConnected(agentPackageName, agent);
11962 } catch (RemoteException e) {
11963 // can't happen; the backup manager service is local
11964 } catch (Exception e) {
11965 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11966 e.printStackTrace();
11967 } finally {
11968 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011969 }
11970 }
11971
11972 // done with this agent
11973 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011974 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011975 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011976 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011977 return;
11978 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011979
11980 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011981 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011982 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011983 return;
11984 }
11985
Christopher Tate181fafa2009-05-14 11:12:14 -070011986 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011987 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011988 return;
11989 }
11990
Christopher Tate6fa95972009-06-05 18:43:55 -070011991 ProcessRecord proc = mBackupTarget.app;
11992 mBackupTarget = null;
11993 mBackupAppName = null;
11994
11995 // Not backing this app up any more; reset its OOM adjustment
11996 updateOomAdjLocked(proc);
11997
Christopher Tatec7b31e32009-06-10 15:49:30 -070011998 // If the app crashed during backup, 'thread' will be null here
11999 if (proc.thread != null) {
12000 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012001 proc.thread.scheduleDestroyBackupAgent(appInfo,
12002 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012003 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012004 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012005 e.printStackTrace();
12006 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012007 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012008 }
12009 }
12010 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012011 // BROADCASTS
12012 // =========================================================
12013
Josh Bartel7f208742010-02-25 11:01:44 -060012014 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012015 List cur) {
12016 final ContentResolver resolver = mContext.getContentResolver();
12017 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12018 if (list == null) {
12019 return cur;
12020 }
12021 int N = list.size();
12022 for (int i=0; i<N; i++) {
12023 Intent intent = list.get(i);
12024 if (filter.match(resolver, intent, true, TAG) >= 0) {
12025 if (cur == null) {
12026 cur = new ArrayList<Intent>();
12027 }
12028 cur.add(intent);
12029 }
12030 }
12031 return cur;
12032 }
12033
Christopher Tatef46723b2012-01-26 14:19:24 -080012034 boolean isPendingBroadcastProcessLocked(int pid) {
12035 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12036 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012038
Christopher Tatef46723b2012-01-26 14:19:24 -080012039 void skipPendingBroadcastLocked(int pid) {
12040 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12041 for (BroadcastQueue queue : mBroadcastQueues) {
12042 queue.skipPendingBroadcastLocked(pid);
12043 }
12044 }
12045
12046 // The app just attached; send any pending broadcasts that it should receive
12047 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12048 boolean didSomething = false;
12049 for (BroadcastQueue queue : mBroadcastQueues) {
12050 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012051 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012052 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012053 }
12054
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012055 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012057 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 synchronized(this) {
12059 ProcessRecord callerApp = null;
12060 if (caller != null) {
12061 callerApp = getRecordForAppLocked(caller);
12062 if (callerApp == null) {
12063 throw new SecurityException(
12064 "Unable to find app for caller " + caller
12065 + " (pid=" + Binder.getCallingPid()
12066 + ") when registering receiver " + receiver);
12067 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012068 if (callerApp.info.uid != Process.SYSTEM_UID &&
12069 !callerApp.pkgList.contains(callerPackage)) {
12070 throw new SecurityException("Given caller package " + callerPackage
12071 + " is not running in process " + callerApp);
12072 }
12073 } else {
12074 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 }
12076
12077 List allSticky = null;
12078
12079 // Look for any matching sticky broadcasts...
12080 Iterator actions = filter.actionsIterator();
12081 if (actions != null) {
12082 while (actions.hasNext()) {
12083 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012084 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012085 }
12086 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012087 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 }
12089
12090 // The first sticky in the list is returned directly back to
12091 // the client.
12092 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12093
Joe Onorato8a9b2202010-02-26 18:56:32 -080012094 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 + ": " + sticky);
12096
12097 if (receiver == null) {
12098 return sticky;
12099 }
12100
12101 ReceiverList rl
12102 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12103 if (rl == null) {
12104 rl = new ReceiverList(this, callerApp,
12105 Binder.getCallingPid(),
12106 Binder.getCallingUid(), receiver);
12107 if (rl.app != null) {
12108 rl.app.receivers.add(rl);
12109 } else {
12110 try {
12111 receiver.asBinder().linkToDeath(rl, 0);
12112 } catch (RemoteException e) {
12113 return sticky;
12114 }
12115 rl.linkedToDeath = true;
12116 }
12117 mRegisteredReceivers.put(receiver.asBinder(), rl);
12118 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012119 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012120 rl.add(bf);
12121 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012122 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 }
12124 mReceiverResolver.addFilter(bf);
12125
12126 // Enqueue broadcasts for all existing stickies that match
12127 // this filter.
12128 if (allSticky != null) {
12129 ArrayList receivers = new ArrayList();
12130 receivers.add(bf);
12131
12132 int N = allSticky.size();
12133 for (int i=0; i<N; i++) {
12134 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012135 BroadcastQueue queue = broadcastQueueForIntent(intent);
12136 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012137 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012138 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012139 queue.enqueueParallelBroadcastLocked(r);
12140 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012141 }
12142 }
12143
12144 return sticky;
12145 }
12146 }
12147
12148 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012149 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012150
Christopher Tatef46723b2012-01-26 14:19:24 -080012151 final long origId = Binder.clearCallingIdentity();
12152 try {
12153 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012154
Christopher Tatef46723b2012-01-26 14:19:24 -080012155 synchronized(this) {
12156 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012157 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012158 if (rl != null) {
12159 if (rl.curBroadcast != null) {
12160 BroadcastRecord r = rl.curBroadcast;
12161 final boolean doNext = finishReceiverLocked(
12162 receiver.asBinder(), r.resultCode, r.resultData,
12163 r.resultExtras, r.resultAbort, true);
12164 if (doNext) {
12165 doTrim = true;
12166 r.queue.processNextBroadcast(false);
12167 }
12168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169
Christopher Tatef46723b2012-01-26 14:19:24 -080012170 if (rl.app != null) {
12171 rl.app.receivers.remove(rl);
12172 }
12173 removeReceiverLocked(rl);
12174 if (rl.linkedToDeath) {
12175 rl.linkedToDeath = false;
12176 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012178 }
12179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012180
Christopher Tatef46723b2012-01-26 14:19:24 -080012181 // If we actually concluded any broadcasts, we might now be able
12182 // to trim the recipients' apps from our working set
12183 if (doTrim) {
12184 trimApplications();
12185 return;
12186 }
12187
12188 } finally {
12189 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 }
12192
12193 void removeReceiverLocked(ReceiverList rl) {
12194 mRegisteredReceivers.remove(rl.receiver.asBinder());
12195 int N = rl.size();
12196 for (int i=0; i<N; i++) {
12197 mReceiverResolver.removeFilter(rl.get(i));
12198 }
12199 }
12200
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012201 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12202 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12203 ProcessRecord r = mLruProcesses.get(i);
12204 if (r.thread != null) {
12205 try {
12206 r.thread.dispatchPackageBroadcast(cmd, packages);
12207 } catch (RemoteException ex) {
12208 }
12209 }
12210 }
12211 }
12212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 private final int broadcastIntentLocked(ProcessRecord callerApp,
12214 String callerPackage, Intent intent, String resolvedType,
12215 IIntentReceiver resultTo, int resultCode, String resultData,
12216 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012217 boolean ordered, boolean sticky, int callingPid, int callingUid,
12218 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012219 intent = new Intent(intent);
12220
Dianne Hackborne7f97212011-02-24 14:40:20 -080012221 // By default broadcasts do not go to stopped apps.
12222 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12223
Joe Onorato8a9b2202010-02-26 18:56:32 -080012224 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12226 + " ordered=" + ordered);
12227 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012228 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 }
12230
12231 // Handle special intents: if this broadcast is from the package
12232 // manager about a package being removed, we need to remove all of
12233 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012234 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012236 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12237 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012238 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239 || uidRemoved) {
12240 if (checkComponentPermission(
12241 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012242 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012243 == PackageManager.PERMISSION_GRANTED) {
12244 if (uidRemoved) {
12245 final Bundle intentExtras = intent.getExtras();
12246 final int uid = intentExtras != null
12247 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12248 if (uid >= 0) {
12249 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12250 synchronized (bs) {
12251 bs.removeUidStatsLocked(uid);
12252 }
12253 }
12254 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012255 // If resources are unvailble just force stop all
12256 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012257 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012258 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12259 if (list != null && (list.length > 0)) {
12260 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012261 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012262 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012263 sendPackageBroadcastLocked(
12264 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012265 }
12266 } else {
12267 Uri data = intent.getData();
12268 String ssp;
12269 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12270 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12271 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012272 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012273 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012274 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012275 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12276 new String[] {ssp});
12277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012278 }
12279 }
12280 }
12281 } else {
12282 String msg = "Permission Denial: " + intent.getAction()
12283 + " broadcast from " + callerPackage + " (pid=" + callingPid
12284 + ", uid=" + callingUid + ")"
12285 + " requires "
12286 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012287 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012288 throw new SecurityException(msg);
12289 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012290
12291 // Special case for adding a package: by default turn on compatibility
12292 // mode.
12293 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012294 Uri data = intent.getData();
12295 String ssp;
12296 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12297 mCompatModePackages.handlePackageAddedLocked(ssp,
12298 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300 }
12301
12302 /*
12303 * If this is the time zone changed action, queue up a message that will reset the timezone
12304 * of all currently running processes. This message will get queued up before the broadcast
12305 * happens.
12306 */
12307 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12308 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12309 }
12310
Robert Greenwalt03595d02010-11-02 14:08:23 -070012311 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12312 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12313 }
12314
Robert Greenwalt434203a2010-10-11 16:00:27 -070012315 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12316 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12317 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12318 }
12319
Dianne Hackborn854060af2009-07-09 18:14:31 -070012320 /*
12321 * Prevent non-system code (defined here to be non-persistent
12322 * processes) from sending protected broadcasts.
12323 */
12324 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12325 || callingUid == Process.SHELL_UID || callingUid == 0) {
12326 // Always okay.
12327 } else if (callerApp == null || !callerApp.persistent) {
12328 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012329 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012330 intent.getAction())) {
12331 String msg = "Permission Denial: not allowed to send broadcast "
12332 + intent.getAction() + " from pid="
12333 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012334 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012335 throw new SecurityException(msg);
12336 }
12337 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012338 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012339 return BROADCAST_SUCCESS;
12340 }
12341 }
12342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343 // Add to the sticky list if requested.
12344 if (sticky) {
12345 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12346 callingPid, callingUid)
12347 != PackageManager.PERMISSION_GRANTED) {
12348 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12349 + callingPid + ", uid=" + callingUid
12350 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012351 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012352 throw new SecurityException(msg);
12353 }
12354 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012355 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012356 + " and enforce permission " + requiredPermission);
12357 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12358 }
12359 if (intent.getComponent() != null) {
12360 throw new SecurityException(
12361 "Sticky broadcasts can't target a specific component");
12362 }
12363 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12364 if (list == null) {
12365 list = new ArrayList<Intent>();
12366 mStickyBroadcasts.put(intent.getAction(), list);
12367 }
12368 int N = list.size();
12369 int i;
12370 for (i=0; i<N; i++) {
12371 if (intent.filterEquals(list.get(i))) {
12372 // This sticky already exists, replace it.
12373 list.set(i, new Intent(intent));
12374 break;
12375 }
12376 }
12377 if (i >= N) {
12378 list.add(new Intent(intent));
12379 }
12380 }
12381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012382 // Figure out who all will receive this broadcast.
12383 List receivers = null;
12384 List<BroadcastFilter> registeredReceivers = null;
12385 try {
12386 if (intent.getComponent() != null) {
12387 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012388 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012389 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 if (ai != null) {
12391 receivers = new ArrayList();
12392 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012393 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 receivers.add(ri);
12395 }
12396 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012397 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012398 // Need to resolve the intent to interested receivers...
12399 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12400 == 0) {
12401 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012402 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012403 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012404 }
Mihai Preda074edef2009-05-18 17:13:31 +020012405 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012406 }
12407 } catch (RemoteException ex) {
12408 // pm is in same process, this will never happen.
12409 }
12410
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012411 final boolean replacePending =
12412 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12413
Joe Onorato8a9b2202010-02-26 18:56:32 -080012414 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012415 + " replacePending=" + replacePending);
12416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012417 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12418 if (!ordered && NR > 0) {
12419 // If we are not serializing this broadcast, then send the
12420 // registered receivers separately so they don't wait for the
12421 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012422 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12423 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012424 callerPackage, callingPid, callingUid, requiredPermission,
12425 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012426 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012427 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012428 TAG, "Enqueueing parallel broadcast " + r);
12429 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012430 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012431 queue.enqueueParallelBroadcastLocked(r);
12432 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434 registeredReceivers = null;
12435 NR = 0;
12436 }
12437
12438 // Merge into one list.
12439 int ir = 0;
12440 if (receivers != null) {
12441 // A special case for PACKAGE_ADDED: do not allow the package
12442 // being added to see this broadcast. This prevents them from
12443 // using this as a back door to get run as soon as they are
12444 // installed. Maybe in the future we want to have a special install
12445 // broadcast or such for apps, but we'd like to deliberately make
12446 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012447 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012448 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12449 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12450 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012451 Uri data = intent.getData();
12452 if (data != null) {
12453 String pkgName = data.getSchemeSpecificPart();
12454 if (pkgName != null) {
12455 skipPackages = new String[] { pkgName };
12456 }
12457 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012458 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012459 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012460 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012461 if (skipPackages != null && (skipPackages.length > 0)) {
12462 for (String skipPackage : skipPackages) {
12463 if (skipPackage != null) {
12464 int NT = receivers.size();
12465 for (int it=0; it<NT; it++) {
12466 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12467 if (curt.activityInfo.packageName.equals(skipPackage)) {
12468 receivers.remove(it);
12469 it--;
12470 NT--;
12471 }
12472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012473 }
12474 }
12475 }
12476
12477 int NT = receivers != null ? receivers.size() : 0;
12478 int it = 0;
12479 ResolveInfo curt = null;
12480 BroadcastFilter curr = null;
12481 while (it < NT && ir < NR) {
12482 if (curt == null) {
12483 curt = (ResolveInfo)receivers.get(it);
12484 }
12485 if (curr == null) {
12486 curr = registeredReceivers.get(ir);
12487 }
12488 if (curr.getPriority() >= curt.priority) {
12489 // Insert this broadcast record into the final list.
12490 receivers.add(it, curr);
12491 ir++;
12492 curr = null;
12493 it++;
12494 NT++;
12495 } else {
12496 // Skip to the next ResolveInfo in the final list.
12497 it++;
12498 curt = null;
12499 }
12500 }
12501 }
12502 while (ir < NR) {
12503 if (receivers == null) {
12504 receivers = new ArrayList();
12505 }
12506 receivers.add(registeredReceivers.get(ir));
12507 ir++;
12508 }
12509
12510 if ((receivers != null && receivers.size() > 0)
12511 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012512 BroadcastQueue queue = broadcastQueueForIntent(intent);
12513 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012514 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012515 receivers, resultTo, resultCode, resultData, map, ordered,
12516 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012517 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012519 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012520 if (DEBUG_BROADCAST) {
12521 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012522 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012524 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012525 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012526 queue.enqueueOrderedBroadcastLocked(r);
12527 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529 }
12530
12531 return BROADCAST_SUCCESS;
12532 }
12533
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012534 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 // Refuse possible leaked file descriptors
12536 if (intent != null && intent.hasFileDescriptors() == true) {
12537 throw new IllegalArgumentException("File descriptors passed in Intent");
12538 }
12539
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012540 int flags = intent.getFlags();
12541
12542 if (!mProcessesReady) {
12543 // if the caller really truly claims to know what they're doing, go
12544 // ahead and allow the broadcast without launching any receivers
12545 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12546 intent = new Intent(intent);
12547 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12548 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12549 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12550 + " before boot completion");
12551 throw new IllegalStateException("Cannot broadcast before boot completed");
12552 }
12553 }
12554
12555 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12556 throw new IllegalArgumentException(
12557 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12558 }
12559
12560 return intent;
12561 }
12562
12563 public final int broadcastIntent(IApplicationThread caller,
12564 Intent intent, String resolvedType, IIntentReceiver resultTo,
12565 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012566 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012567 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012568 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012569 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012571 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12572 final int callingPid = Binder.getCallingPid();
12573 final int callingUid = Binder.getCallingUid();
12574 final long origId = Binder.clearCallingIdentity();
12575 int res = broadcastIntentLocked(callerApp,
12576 callerApp != null ? callerApp.info.packageName : null,
12577 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012578 resultCode, resultData, map, requiredPermission, serialized, sticky,
12579 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012580 Binder.restoreCallingIdentity(origId);
12581 return res;
12582 }
12583 }
12584
12585 int broadcastIntentInPackage(String packageName, int uid,
12586 Intent intent, String resolvedType, IIntentReceiver resultTo,
12587 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012588 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012590 intent = verifyBroadcastLocked(intent);
12591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012592 final long origId = Binder.clearCallingIdentity();
12593 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12594 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012595 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012596 Binder.restoreCallingIdentity(origId);
12597 return res;
12598 }
12599 }
12600
Amith Yamasani742a6712011-05-04 14:49:28 -070012601 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12602 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012603 // Refuse possible leaked file descriptors
12604 if (intent != null && intent.hasFileDescriptors() == true) {
12605 throw new IllegalArgumentException("File descriptors passed in Intent");
12606 }
12607
12608 synchronized(this) {
12609 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12610 != PackageManager.PERMISSION_GRANTED) {
12611 String msg = "Permission Denial: unbroadcastIntent() from pid="
12612 + Binder.getCallingPid()
12613 + ", uid=" + Binder.getCallingUid()
12614 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012615 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012616 throw new SecurityException(msg);
12617 }
12618 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12619 if (list != null) {
12620 int N = list.size();
12621 int i;
12622 for (i=0; i<N; i++) {
12623 if (intent.filterEquals(list.get(i))) {
12624 list.remove(i);
12625 break;
12626 }
12627 }
12628 }
12629 }
12630 }
12631
12632 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12633 String resultData, Bundle resultExtras, boolean resultAbort,
12634 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012635 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12636 if (r == null) {
12637 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 return false;
12639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640
Christopher Tatef46723b2012-01-26 14:19:24 -080012641 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12642 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012643 }
12644
12645 public void finishReceiver(IBinder who, int resultCode, String resultData,
12646 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012647 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648
12649 // Refuse possible leaked file descriptors
12650 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12651 throw new IllegalArgumentException("File descriptors passed in Bundle");
12652 }
12653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012654 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012655 try {
12656 boolean doNext = false;
12657 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658
Christopher Tatef46723b2012-01-26 14:19:24 -080012659 synchronized(this) {
12660 r = broadcastRecordForReceiverLocked(who);
12661 if (r != null) {
12662 doNext = r.queue.finishReceiverLocked(r, resultCode,
12663 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012665 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012666
Christopher Tatef46723b2012-01-26 14:19:24 -080012667 if (doNext) {
12668 r.queue.processNextBroadcast(false);
12669 }
12670 trimApplications();
12671 } finally {
12672 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012676 // =========================================================
12677 // INSTRUMENTATION
12678 // =========================================================
12679
12680 public boolean startInstrumentation(ComponentName className,
12681 String profileFile, int flags, Bundle arguments,
12682 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012683 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684 // Refuse possible leaked file descriptors
12685 if (arguments != null && arguments.hasFileDescriptors()) {
12686 throw new IllegalArgumentException("File descriptors passed in Bundle");
12687 }
12688
12689 synchronized(this) {
12690 InstrumentationInfo ii = null;
12691 ApplicationInfo ai = null;
12692 try {
12693 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012694 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012696 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012697 } catch (PackageManager.NameNotFoundException e) {
12698 }
12699 if (ii == null) {
12700 reportStartInstrumentationFailure(watcher, className,
12701 "Unable to find instrumentation info for: " + className);
12702 return false;
12703 }
12704 if (ai == null) {
12705 reportStartInstrumentationFailure(watcher, className,
12706 "Unable to find instrumentation target package: " + ii.targetPackage);
12707 return false;
12708 }
12709
12710 int match = mContext.getPackageManager().checkSignatures(
12711 ii.targetPackage, ii.packageName);
12712 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12713 String msg = "Permission Denial: starting instrumentation "
12714 + className + " from pid="
12715 + Binder.getCallingPid()
12716 + ", uid=" + Binder.getCallingPid()
12717 + " not allowed because package " + ii.packageName
12718 + " does not have a signature matching the target "
12719 + ii.targetPackage;
12720 reportStartInstrumentationFailure(watcher, className, msg);
12721 throw new SecurityException(msg);
12722 }
12723
12724 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012725 // Instrumentation can kill and relaunch even persistent processes
12726 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012727 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012728 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012729 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012730 app.instrumentationProfileFile = profileFile;
12731 app.instrumentationArguments = arguments;
12732 app.instrumentationWatcher = watcher;
12733 app.instrumentationResultClass = className;
12734 Binder.restoreCallingIdentity(origId);
12735 }
12736
12737 return true;
12738 }
12739
12740 /**
12741 * Report errors that occur while attempting to start Instrumentation. Always writes the
12742 * error to the logs, but if somebody is watching, send the report there too. This enables
12743 * the "am" command to report errors with more information.
12744 *
12745 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12746 * @param cn The component name of the instrumentation.
12747 * @param report The error report.
12748 */
12749 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12750 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012751 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752 try {
12753 if (watcher != null) {
12754 Bundle results = new Bundle();
12755 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12756 results.putString("Error", report);
12757 watcher.instrumentationStatus(cn, -1, results);
12758 }
12759 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012760 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012761 }
12762 }
12763
12764 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12765 if (app.instrumentationWatcher != null) {
12766 try {
12767 // NOTE: IInstrumentationWatcher *must* be oneway here
12768 app.instrumentationWatcher.instrumentationFinished(
12769 app.instrumentationClass,
12770 resultCode,
12771 results);
12772 } catch (RemoteException e) {
12773 }
12774 }
12775 app.instrumentationWatcher = null;
12776 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012777 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012778 app.instrumentationProfileFile = null;
12779 app.instrumentationArguments = null;
12780
Christopher Tate3dacd842011-08-19 14:56:15 -070012781 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012782 }
12783
12784 public void finishInstrumentation(IApplicationThread target,
12785 int resultCode, Bundle results) {
12786 // Refuse possible leaked file descriptors
12787 if (results != null && results.hasFileDescriptors()) {
12788 throw new IllegalArgumentException("File descriptors passed in Intent");
12789 }
12790
12791 synchronized(this) {
12792 ProcessRecord app = getRecordForAppLocked(target);
12793 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012794 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 return;
12796 }
12797 final long origId = Binder.clearCallingIdentity();
12798 finishInstrumentationLocked(app, resultCode, results);
12799 Binder.restoreCallingIdentity(origId);
12800 }
12801 }
12802
12803 // =========================================================
12804 // CONFIGURATION
12805 // =========================================================
12806
12807 public ConfigurationInfo getDeviceConfigurationInfo() {
12808 ConfigurationInfo config = new ConfigurationInfo();
12809 synchronized (this) {
12810 config.reqTouchScreen = mConfiguration.touchscreen;
12811 config.reqKeyboardType = mConfiguration.keyboard;
12812 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012813 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12814 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012815 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12816 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012817 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12818 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12820 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012821 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012822 }
12823 return config;
12824 }
12825
12826 public Configuration getConfiguration() {
12827 Configuration ci;
12828 synchronized(this) {
12829 ci = new Configuration(mConfiguration);
12830 }
12831 return ci;
12832 }
12833
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012834 public void updatePersistentConfiguration(Configuration values) {
12835 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12836 "updateConfiguration()");
12837 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12838 "updateConfiguration()");
12839 if (values == null) {
12840 throw new NullPointerException("Configuration must not be null");
12841 }
12842
12843 synchronized(this) {
12844 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012845 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012846 Binder.restoreCallingIdentity(origId);
12847 }
12848 }
12849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012850 public void updateConfiguration(Configuration values) {
12851 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12852 "updateConfiguration()");
12853
12854 synchronized(this) {
12855 if (values == null && mWindowManager != null) {
12856 // sentinel: fetch the current configuration from the window manager
12857 values = mWindowManager.computeNewConfiguration();
12858 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012859
12860 if (mWindowManager != null) {
12861 mProcessList.applyDisplaySize(mWindowManager);
12862 }
12863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012865 if (values != null) {
12866 Settings.System.clearConfiguration(values);
12867 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012868 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 Binder.restoreCallingIdentity(origId);
12870 }
12871 }
12872
12873 /**
12874 * Do either or both things: (1) change the current configuration, and (2)
12875 * make sure the given activity is running with the (now) current
12876 * configuration. Returns true if the activity has been left running, or
12877 * false if <var>starting</var> is being destroyed to match the new
12878 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012879 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012880 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012881 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012882 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012883 // do nothing if we are headless
12884 if (mHeadless) return true;
12885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012886 int changes = 0;
12887
12888 boolean kept = true;
12889
12890 if (values != null) {
12891 Configuration newConfig = new Configuration(mConfiguration);
12892 changes = newConfig.updateFrom(values);
12893 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012894 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012895 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012896 }
12897
Doug Zongker2bec3d42009-12-04 12:52:44 -080012898 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012899
Dianne Hackborn813075a62011-11-14 17:45:19 -080012900 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 saveLocaleLocked(values.locale,
12902 !values.locale.equals(mConfiguration.locale),
12903 values.userSetLocale);
12904 }
12905
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012906 mConfigurationSeq++;
12907 if (mConfigurationSeq <= 0) {
12908 mConfigurationSeq = 1;
12909 }
12910 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012911 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012912 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012913
12914 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012915
12916 // TODO: If our config changes, should we auto dismiss any currently
12917 // showing dialogs?
12918 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012919
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012920 AttributeCache ac = AttributeCache.instance();
12921 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012922 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012925 // Make sure all resources in our process are updated
12926 // right now, so that anyone who is going to retrieve
12927 // resource values after we return will be sure to get
12928 // the new ones. This is especially important during
12929 // boot, where the first config change needs to guarantee
12930 // all resources have that config before following boot
12931 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012932 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012933
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012934 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012935 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012936 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012937 mHandler.sendMessage(msg);
12938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012940 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12941 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 try {
12943 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012944 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012945 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012946 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 }
12948 } catch (Exception e) {
12949 }
12950 }
12951 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012952 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12953 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012954 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012955 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012956 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12957 broadcastIntentLocked(null, null,
12958 new Intent(Intent.ACTION_LOCALE_CHANGED),
12959 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070012960 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 }
12963 }
12964
12965 if (changes != 0 && starting == null) {
12966 // If the configuration changed, and the caller is not already
12967 // in the process of starting an activity, then find the top
12968 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012969 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012970 }
12971
12972 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012973 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012974 // And we need to make sure at this point that all other activities
12975 // are made visible with the correct configuration.
12976 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 }
12978
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012979 if (values != null && mWindowManager != null) {
12980 mWindowManager.setNewConfiguration(mConfiguration);
12981 }
12982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012983 return kept;
12984 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012985
12986 /**
12987 * Decide based on the configuration whether we should shouw the ANR,
12988 * crash, etc dialogs. The idea is that if there is no affordnace to
12989 * press the on-screen buttons, we shouldn't show the dialog.
12990 *
12991 * A thought: SystemUI might also want to get told about this, the Power
12992 * dialog / global actions also might want different behaviors.
12993 */
12994 private static final boolean shouldShowDialogs(Configuration config) {
12995 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12996 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998
12999 /**
13000 * Save the locale. You must be inside a synchronized (this) block.
13001 */
13002 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13003 if(isDiff) {
13004 SystemProperties.set("user.language", l.getLanguage());
13005 SystemProperties.set("user.region", l.getCountry());
13006 }
13007
13008 if(isPersist) {
13009 SystemProperties.set("persist.sys.language", l.getLanguage());
13010 SystemProperties.set("persist.sys.country", l.getCountry());
13011 SystemProperties.set("persist.sys.localevar", l.getVariant());
13012 }
13013 }
13014
13015 // =========================================================
13016 // LIFETIME MANAGEMENT
13017 // =========================================================
13018
Christopher Tatef46723b2012-01-26 14:19:24 -080013019 // Returns which broadcast queue the app is the current [or imminent] receiver
13020 // on, or 'null' if the app is not an active broadcast recipient.
13021 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13022 BroadcastRecord r = app.curReceiver;
13023 if (r != null) {
13024 return r.queue;
13025 }
13026
13027 // It's not the current receiver, but it might be starting up to become one
13028 synchronized (this) {
13029 for (BroadcastQueue queue : mBroadcastQueues) {
13030 r = queue.mPendingBroadcast;
13031 if (r != null && r.curApp == app) {
13032 // found it; report which queue it's in
13033 return queue;
13034 }
13035 }
13036 }
13037
13038 return null;
13039 }
13040
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013041 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013042 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013043 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013044 // This adjustment has already been computed. If we are calling
13045 // from the top, we may have already computed our adjustment with
13046 // an earlier hidden adjustment that isn't really for us... if
13047 // so, use the new hidden adjustment.
13048 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013049 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013050 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013051 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013052 }
13053
13054 if (app.thread == null) {
13055 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013056 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013057 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013058 }
13059
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013060 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13061 app.adjSource = null;
13062 app.adjTarget = null;
13063 app.empty = false;
13064 app.hidden = false;
13065
13066 final int activitiesSize = app.activities.size();
13067
Dianne Hackborn7d608422011-08-07 16:24:18 -070013068 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013069 // The max adjustment doesn't allow this app to be anything
13070 // below foreground, so it is not worth doing work for it.
13071 app.adjType = "fixed";
13072 app.adjSeq = mAdjSeq;
13073 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013074 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013075 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013076 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013077 // System process can do UI, and when they do we want to have
13078 // them trim their memory after the user leaves the UI. To
13079 // facilitate this, here we need to determine whether or not it
13080 // is currently showing UI.
13081 app.systemNoUi = true;
13082 if (app == TOP_APP) {
13083 app.systemNoUi = false;
13084 } else if (activitiesSize > 0) {
13085 for (int j = 0; j < activitiesSize; j++) {
13086 final ActivityRecord r = app.activities.get(j);
13087 if (r.visible) {
13088 app.systemNoUi = false;
13089 break;
13090 }
13091 }
13092 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013093 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013094 }
13095
13096 final boolean hadForegroundActivities = app.foregroundActivities;
13097
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013098 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013099 app.keeping = false;
13100 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013101
The Android Open Source Project4df24232009-03-05 14:34:35 -080013102 // Determine the importance of the process, starting with most
13103 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013105 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013106 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013107 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013108 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013109 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013110 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013111 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013112 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013113 } else if (app.instrumentationClass != null) {
13114 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013115 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013116 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013117 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013118 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013119 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013120 // counts as being in the foreground for OOM killer purposes.
13121 // It's placed in a sched group based on the nature of the
13122 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013123 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013124 schedGroup = (queue == mFgBroadcastQueue)
13125 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013126 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013127 } else if (app.executingServices.size() > 0) {
13128 // An app that is currently executing a service callback also
13129 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013130 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013131 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013132 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013133 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013134 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013135 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013136 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013137 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013138 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013139 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013140 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013141 // A very not-needed process. If this is lower in the lru list,
13142 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013143 adj = hiddenAdj;
13144 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013145 app.hidden = true;
13146 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013147 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013148 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013149
13150 // Examine all activities if not already foreground.
13151 if (!app.foregroundActivities && activitiesSize > 0) {
13152 for (int j = 0; j < activitiesSize; j++) {
13153 final ActivityRecord r = app.activities.get(j);
13154 if (r.visible) {
13155 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013156 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13157 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013158 app.adjType = "visible";
13159 }
13160 schedGroup = Process.THREAD_GROUP_DEFAULT;
13161 app.hidden = false;
13162 app.foregroundActivities = true;
13163 break;
13164 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13165 || r.state == ActivityState.STOPPING) {
13166 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013167 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13168 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013169 app.adjType = "stopping";
13170 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013171 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013172 app.foregroundActivities = true;
13173 }
13174 }
13175 }
13176
Dianne Hackborn7d608422011-08-07 16:24:18 -070013177 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013178 if (app.foregroundServices) {
13179 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013180 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013181 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013182 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013183 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013184 } else if (app.forcingToForeground != null) {
13185 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013186 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013187 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013188 app.adjType = "force-foreground";
13189 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013190 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013191 }
13192 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013193
Dianne Hackborn7d608422011-08-07 16:24:18 -070013194 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013195 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013196 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013197 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013198 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013199 app.adjType = "heavy";
13200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013201
Dianne Hackborn7d608422011-08-07 16:24:18 -070013202 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013203 // This process is hosting what we currently consider to be the
13204 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013205 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013206 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013207 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013208 app.adjType = "home";
13209 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013210
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013211 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13212 && app.activities.size() > 0) {
13213 // This was the previous process that showed UI to the user.
13214 // We want to try to keep it around more aggressively, to give
13215 // a good experience around switching between two apps.
13216 adj = ProcessList.PREVIOUS_APP_ADJ;
13217 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13218 app.hidden = false;
13219 app.adjType = "previous";
13220 }
13221
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013222 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13223 + " reason=" + app.adjType);
13224
The Android Open Source Project4df24232009-03-05 14:34:35 -080013225 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013226 // there are applications dependent on our services or providers, but
13227 // this gives us a baseline and makes sure we don't get into an
13228 // infinite recursion.
13229 app.adjSeq = mAdjSeq;
13230 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013231
Christopher Tate6fa95972009-06-05 18:43:55 -070013232 if (mBackupTarget != null && app == mBackupTarget.app) {
13233 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013234 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013235 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013236 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013237 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013238 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013239 }
13240 }
13241
Dianne Hackborn7d608422011-08-07 16:24:18 -070013242 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013243 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013244 final long now = SystemClock.uptimeMillis();
13245 // This process is more important if the top activity is
13246 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013247 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013248 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013249 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013250 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013251 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013252 // If this process has shown some UI, let it immediately
13253 // go to the LRU list because it may be pretty heavy with
13254 // UI stuff. We'll tag it with a label just to help
13255 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013256 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013257 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013258 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013259 } else {
13260 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13261 // This service has seen some activity within
13262 // recent memory, so we will keep its process ahead
13263 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013264 if (adj > ProcessList.SERVICE_ADJ) {
13265 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013266 app.adjType = "started-services";
13267 app.hidden = false;
13268 }
13269 }
13270 // If we have let the service slide into the background
13271 // state, still have some text describing what it is doing
13272 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013273 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013274 app.adjType = "started-bg-services";
13275 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013276 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013277 // Don't kill this process because it is doing work; it
13278 // has said it is doing work.
13279 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013280 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013281 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013282 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013283 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013284 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013285 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013286 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013287 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013288 // XXX should compute this based on the max of
13289 // all connected clients.
13290 ConnectionRecord cr = clist.get(i);
13291 if (cr.binding.client == app) {
13292 // Binding to ourself is not interesting.
13293 continue;
13294 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013295 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013296 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013297 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013298 int myHiddenAdj = hiddenAdj;
13299 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013300 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013301 myHiddenAdj = client.hiddenAdj;
13302 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013303 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013304 }
13305 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013306 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013307 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013308 String adjType = null;
13309 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13310 // Not doing bind OOM management, so treat
13311 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013312 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013313 // If this process has shown some UI, let it immediately
13314 // go to the LRU list because it may be pretty heavy with
13315 // UI stuff. We'll tag it with a label just to help
13316 // debug and understand what is going on.
13317 if (adj > clientAdj) {
13318 adjType = "bound-bg-ui-services";
13319 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013320 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013321 clientAdj = adj;
13322 } else {
13323 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13324 // This service has not seen activity within
13325 // recent memory, so allow it to drop to the
13326 // LRU list if there is no other reason to keep
13327 // it around. We'll also tag it with a label just
13328 // to help debug and undertand what is going on.
13329 if (adj > clientAdj) {
13330 adjType = "bound-bg-services";
13331 }
13332 clientAdj = adj;
13333 }
13334 }
13335 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013336 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013337 // If this process has recently shown UI, and
13338 // the process that is binding to it is less
13339 // important than being visible, then we don't
13340 // care about the binding as much as we care
13341 // about letting this process get into the LRU
13342 // list to be killed and restarted if needed for
13343 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013344 if (app.hasShownUi && app != mHomeProcess
13345 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013346 adjType = "bound-bg-ui-services";
13347 } else {
13348 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13349 |Context.BIND_IMPORTANT)) != 0) {
13350 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013351 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13352 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13353 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13354 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13355 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013356 adj = clientAdj;
13357 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013358 app.pendingUiClean = true;
13359 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13360 adj = ProcessList.VISIBLE_APP_ADJ;
13361 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013362 }
13363 if (!client.hidden) {
13364 app.hidden = false;
13365 }
13366 if (client.keeping) {
13367 app.keeping = true;
13368 }
13369 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013370 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013371 }
13372 if (adjType != null) {
13373 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013374 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13375 .REASON_SERVICE_IN_USE;
13376 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013377 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013378 app.adjTarget = s.name;
13379 }
13380 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13381 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13382 schedGroup = Process.THREAD_GROUP_DEFAULT;
13383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013384 }
13385 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013386 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13387 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013388 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013389 (a.visible || a.state == ActivityState.RESUMED
13390 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013391 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013392 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13393 schedGroup = Process.THREAD_GROUP_DEFAULT;
13394 }
13395 app.hidden = false;
13396 app.adjType = "service";
13397 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13398 .REASON_SERVICE_IN_USE;
13399 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013400 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013401 app.adjTarget = s.name;
13402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404 }
13405 }
13406 }
13407 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013408
Dianne Hackborn287952c2010-09-22 22:34:31 -070013409 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013410 // would like to avoid killing it unless it would prevent the current
13411 // application from running. By default we put the process in
13412 // with the rest of the background processes; as we scan through
13413 // its services we may bump it up from there.
13414 if (adj > hiddenAdj) {
13415 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013416 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013417 app.adjType = "bg-services";
13418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013419 }
13420
Dianne Hackborn7d608422011-08-07 16:24:18 -070013421 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013422 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013423 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013424 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013425 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013426 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013427 if (cpr.clients.size() != 0) {
13428 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013429 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013430 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013431 if (client == app) {
13432 // Being our own client is not interesting.
13433 continue;
13434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013435 int myHiddenAdj = hiddenAdj;
13436 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013437 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013438 myHiddenAdj = client.hiddenAdj;
13439 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013440 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013441 }
13442 }
13443 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013444 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013445 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013446 if (app.hasShownUi && app != mHomeProcess
13447 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013448 app.adjType = "bg-ui-provider";
13449 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013450 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13451 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013452 app.adjType = "provider";
13453 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013454 if (!client.hidden) {
13455 app.hidden = false;
13456 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013457 if (client.keeping) {
13458 app.keeping = true;
13459 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013460 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13461 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013462 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013463 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013464 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013465 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013466 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13467 schedGroup = Process.THREAD_GROUP_DEFAULT;
13468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013469 }
13470 }
13471 // If the provider has external (non-framework) process
13472 // dependencies, ensure that its adjustment is at least
13473 // FOREGROUND_APP_ADJ.
13474 if (cpr.externals != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013475 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13476 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013477 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013478 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013479 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013480 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013481 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013482 }
13483 }
13484 }
13485 }
13486
13487 app.curRawAdj = adj;
13488
Joe Onorato8a9b2202010-02-26 18:56:32 -080013489 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013490 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13491 if (adj > app.maxAdj) {
13492 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013493 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013494 schedGroup = Process.THREAD_GROUP_DEFAULT;
13495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013497 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013498 app.keeping = true;
13499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013500
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013501 if (app.hasAboveClient) {
13502 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13503 // then we need to drop its adjustment to be lower than the service's
13504 // in order to honor the request. We want to drop it by one adjustment
13505 // level... but there is special meaning applied to various levels so
13506 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013507 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013508 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013509 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13510 adj = ProcessList.VISIBLE_APP_ADJ;
13511 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13512 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13513 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13514 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013515 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013516 adj++;
13517 }
13518 }
13519
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013520 if (adj == ProcessList.SERVICE_ADJ) {
13521 if (doingAll) {
13522 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13523 mNewNumServiceProcs++;
13524 }
13525 if (app.serviceb) {
13526 adj = ProcessList.SERVICE_B_ADJ;
13527 }
13528 } else {
13529 app.serviceb = false;
13530 }
13531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013533 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013534
13535 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013536 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13537 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013538 }
13539
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013540 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013541 }
13542
13543 /**
13544 * Ask a given process to GC right now.
13545 */
13546 final void performAppGcLocked(ProcessRecord app) {
13547 try {
13548 app.lastRequestedGc = SystemClock.uptimeMillis();
13549 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013550 if (app.reportLowMemory) {
13551 app.reportLowMemory = false;
13552 app.thread.scheduleLowMemory();
13553 } else {
13554 app.thread.processInBackground();
13555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013556 }
13557 } catch (Exception e) {
13558 // whatever.
13559 }
13560 }
13561
13562 /**
13563 * Returns true if things are idle enough to perform GCs.
13564 */
Josh Bartel7f208742010-02-25 11:01:44 -060013565 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013566 boolean processingBroadcasts = false;
13567 for (BroadcastQueue q : mBroadcastQueues) {
13568 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13569 processingBroadcasts = true;
13570 }
13571 }
13572 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013573 && (mSleeping || (mMainStack.mResumedActivity != null &&
13574 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013575 }
13576
13577 /**
13578 * Perform GCs on all processes that are waiting for it, but only
13579 * if things are idle.
13580 */
13581 final void performAppGcsLocked() {
13582 final int N = mProcessesToGc.size();
13583 if (N <= 0) {
13584 return;
13585 }
Josh Bartel7f208742010-02-25 11:01:44 -060013586 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013587 while (mProcessesToGc.size() > 0) {
13588 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013589 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013590 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13591 <= SystemClock.uptimeMillis()) {
13592 // To avoid spamming the system, we will GC processes one
13593 // at a time, waiting a few seconds between each.
13594 performAppGcLocked(proc);
13595 scheduleAppGcsLocked();
13596 return;
13597 } else {
13598 // It hasn't been long enough since we last GCed this
13599 // process... put it in the list to wait for its time.
13600 addProcessToGcListLocked(proc);
13601 break;
13602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013603 }
13604 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013605
13606 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013607 }
13608 }
13609
13610 /**
13611 * If all looks good, perform GCs on all processes waiting for them.
13612 */
13613 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013614 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013615 performAppGcsLocked();
13616 return;
13617 }
13618 // Still not idle, wait some more.
13619 scheduleAppGcsLocked();
13620 }
13621
13622 /**
13623 * Schedule the execution of all pending app GCs.
13624 */
13625 final void scheduleAppGcsLocked() {
13626 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013627
13628 if (mProcessesToGc.size() > 0) {
13629 // Schedule a GC for the time to the next process.
13630 ProcessRecord proc = mProcessesToGc.get(0);
13631 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13632
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013633 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013634 long now = SystemClock.uptimeMillis();
13635 if (when < (now+GC_TIMEOUT)) {
13636 when = now + GC_TIMEOUT;
13637 }
13638 mHandler.sendMessageAtTime(msg, when);
13639 }
13640 }
13641
13642 /**
13643 * Add a process to the array of processes waiting to be GCed. Keeps the
13644 * list in sorted order by the last GC time. The process can't already be
13645 * on the list.
13646 */
13647 final void addProcessToGcListLocked(ProcessRecord proc) {
13648 boolean added = false;
13649 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13650 if (mProcessesToGc.get(i).lastRequestedGc <
13651 proc.lastRequestedGc) {
13652 added = true;
13653 mProcessesToGc.add(i+1, proc);
13654 break;
13655 }
13656 }
13657 if (!added) {
13658 mProcessesToGc.add(0, proc);
13659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013660 }
13661
13662 /**
13663 * Set up to ask a process to GC itself. This will either do it
13664 * immediately, or put it on the list of processes to gc the next
13665 * time things are idle.
13666 */
13667 final void scheduleAppGcLocked(ProcessRecord app) {
13668 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013669 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013670 return;
13671 }
13672 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013673 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013674 scheduleAppGcsLocked();
13675 }
13676 }
13677
Dianne Hackborn287952c2010-09-22 22:34:31 -070013678 final void checkExcessivePowerUsageLocked(boolean doKills) {
13679 updateCpuStatsNow();
13680
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013681 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013682 boolean doWakeKills = doKills;
13683 boolean doCpuKills = doKills;
13684 if (mLastPowerCheckRealtime == 0) {
13685 doWakeKills = false;
13686 }
13687 if (mLastPowerCheckUptime == 0) {
13688 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013689 }
13690 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013691 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013692 }
13693 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013694 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13695 final long curUptime = SystemClock.uptimeMillis();
13696 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13697 mLastPowerCheckRealtime = curRealtime;
13698 mLastPowerCheckUptime = curUptime;
13699 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13700 doWakeKills = false;
13701 }
13702 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13703 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013704 }
13705 int i = mLruProcesses.size();
13706 while (i > 0) {
13707 i--;
13708 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013709 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013710 long wtime;
13711 synchronized (stats) {
13712 wtime = stats.getProcessWakeTime(app.info.uid,
13713 app.pid, curRealtime);
13714 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013715 long wtimeUsed = wtime - app.lastWakeTime;
13716 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13717 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013718 StringBuilder sb = new StringBuilder(128);
13719 sb.append("Wake for ");
13720 app.toShortString(sb);
13721 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013722 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013723 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013724 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013725 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013726 sb.append((wtimeUsed*100)/realtimeSince);
13727 sb.append("%)");
13728 Slog.i(TAG, sb.toString());
13729 sb.setLength(0);
13730 sb.append("CPU for ");
13731 app.toShortString(sb);
13732 sb.append(": over ");
13733 TimeUtils.formatDuration(uptimeSince, sb);
13734 sb.append(" used ");
13735 TimeUtils.formatDuration(cputimeUsed, sb);
13736 sb.append(" (");
13737 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013738 sb.append("%)");
13739 Slog.i(TAG, sb.toString());
13740 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013741 // If a process has held a wake lock for more
13742 // than 50% of the time during this period,
13743 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013744 if (doWakeKills && realtimeSince > 0
13745 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13746 synchronized (stats) {
13747 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13748 realtimeSince, wtimeUsed);
13749 }
13750 Slog.w(TAG, "Excessive wake lock in " + app.processName
13751 + " (pid " + app.pid + "): held " + wtimeUsed
13752 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013753 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13754 app.processName, app.setAdj, "excessive wake lock");
13755 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013756 } else if (doCpuKills && uptimeSince > 0
13757 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13758 synchronized (stats) {
13759 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13760 uptimeSince, cputimeUsed);
13761 }
13762 Slog.w(TAG, "Excessive CPU in " + app.processName
13763 + " (pid " + app.pid + "): used " + cputimeUsed
13764 + " during " + uptimeSince);
13765 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13766 app.processName, app.setAdj, "excessive cpu");
13767 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013768 } else {
13769 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013770 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013771 }
13772 }
13773 }
13774 }
13775
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013776 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013777 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013778 app.hiddenAdj = hiddenAdj;
13779
13780 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013781 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013782 }
13783
Dianne Hackborn287952c2010-09-22 22:34:31 -070013784 final boolean wasKeeping = app.keeping;
13785
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013786 boolean success = true;
13787
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013788 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013789
Jeff Brown10e89712011-07-08 18:52:57 -070013790 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013791 if (false) {
13792 // Removing for now. Forcing GCs is not so useful anymore
13793 // with Dalvik, and the new memory level hint facility is
13794 // better for what we need to do these days.
13795 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13796 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13797 // If this app is transitioning from foreground to
13798 // non-foreground, have it do a gc.
13799 scheduleAppGcLocked(app);
13800 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13801 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13802 // Likewise do a gc when an app is moving in to the
13803 // background (such as a service stopping).
13804 scheduleAppGcLocked(app);
13805 }
Jeff Brown10e89712011-07-08 18:52:57 -070013806 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013807
Jeff Brown10e89712011-07-08 18:52:57 -070013808 if (wasKeeping && !app.keeping) {
13809 // This app is no longer something we want to keep. Note
13810 // its current wake lock time to later know to kill it if
13811 // it is not behaving well.
13812 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13813 synchronized (stats) {
13814 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13815 app.pid, SystemClock.elapsedRealtime());
13816 }
13817 app.lastCpuTime = app.curCpuTime;
13818 }
13819
13820 app.setRawAdj = app.curRawAdj;
13821 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013822
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013823 if (app.curAdj != app.setAdj) {
13824 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013825 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013826 TAG, "Set " + app.pid + " " + app.processName +
13827 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013828 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013829 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013830 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013831 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013832 }
13833 }
13834 if (app.setSchedGroup != app.curSchedGroup) {
13835 app.setSchedGroup = app.curSchedGroup;
13836 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13837 "Setting process group of " + app.processName
13838 + " to " + app.curSchedGroup);
13839 if (app.waitingToKill != null &&
13840 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13841 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13842 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13843 app.processName, app.setAdj, app.waitingToKill);
13844 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013845 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013846 } else {
13847 if (true) {
13848 long oldId = Binder.clearCallingIdentity();
13849 try {
13850 Process.setProcessGroup(app.pid, app.curSchedGroup);
13851 } catch (Exception e) {
13852 Slog.w(TAG, "Failed setting process group of " + app.pid
13853 + " to " + app.curSchedGroup);
13854 e.printStackTrace();
13855 } finally {
13856 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013857 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013858 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013859 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013860 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013861 app.thread.setSchedulingGroup(app.curSchedGroup);
13862 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013863 }
13864 }
13865 }
13866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013867 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013868 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013869 }
13870
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013871 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013872 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013873 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborncbb722e2012-02-07 18:33:49 -080013874 for (int i=mMainStack.mPausingActivities.size()-1; i>=0; i--) {
13875 ActivityRecord r = mMainStack.mPausingActivities.get(i);
13876 if (r.app != null) {
13877 resumedActivity = r;
13878 break;
13879 }
13880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013881 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013882 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 }
13884 }
13885 return resumedActivity;
13886 }
13887
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013888 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013889 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13891 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013892 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13893 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013894
13895 mAdjSeq++;
13896
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013897 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013898 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13899 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013900 if (nowHidden != wasHidden) {
13901 // Changed to/from hidden state, so apps after it in the LRU
13902 // list may also be changed.
13903 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013904 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013905 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013906 }
13907
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013908 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013909 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013910 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13911
13912 if (false) {
13913 RuntimeException e = new RuntimeException();
13914 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013915 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013916 }
13917
13918 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013919 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013920
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013921 // Let's determine how many processes we have running vs.
13922 // how many slots we have for background processes; we may want
13923 // to put multiple processes in a slot of there are enough of
13924 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013925 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013926 int factor = (mLruProcesses.size()-4)/numSlots;
13927 if (factor < 1) factor = 1;
13928 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013929 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013930
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013931 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013932 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013933 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013934 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013935 while (i > 0) {
13936 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013937 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013938 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013939 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
13940 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013941 && app.curAdj == curHiddenAdj) {
13942 step++;
13943 if (step >= factor) {
13944 step = 0;
13945 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013946 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013947 }
13948 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013949 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013950 numHidden++;
13951 if (numHidden > mProcessLimit) {
13952 Slog.i(TAG, "No longer want " + app.processName
13953 + " (pid " + app.pid + "): hidden #" + numHidden);
13954 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13955 app.processName, app.setAdj, "too many background");
13956 app.killedBackground = true;
13957 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013958 }
13959 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013960 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
13961 // If this is an isolated process, and there are no
13962 // services running in it, then the process is no longer
13963 // needed. We agressively kill these because we can by
13964 // definition not re-use the same process again, and it is
13965 // good to avoid having whatever code was running in them
13966 // left sitting around after no longer needed.
13967 Slog.i(TAG, "Isolated process " + app.processName
13968 + " (pid " + app.pid + ") no longer needed");
13969 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13970 app.processName, app.setAdj, "isolated not needed");
13971 app.killedBackground = true;
13972 Process.killProcessQuiet(app.pid);
13973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013974 }
13975 }
13976
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013977 mNumServiceProcs = mNewNumServiceProcs;
13978
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013979 // Now determine the memory trimming level of background processes.
13980 // Unfortunately we need to start at the back of the list to do this
13981 // properly. We only do this if the number of background apps we
13982 // are managing to keep around is less than half the maximum we desire;
13983 // if we are keeping a good number around, we'll let them use whatever
13984 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013985 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013986 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013987 factor = numHidden/3;
13988 int minFactor = 2;
13989 if (mHomeProcess != null) minFactor++;
13990 if (mPreviousProcess != null) minFactor++;
13991 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013992 step = 0;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013993 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013994 for (i=0; i<N; i++) {
13995 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013996 if (app.curAdj >= ProcessList.HOME_APP_ADJ
13997 && app.curAdj != ProcessList.SERVICE_B_ADJ
13998 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013999 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14000 try {
14001 app.thread.scheduleTrimMemory(curLevel);
14002 } catch (RemoteException e) {
14003 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014004 if (false) {
14005 // For now we won't do this; our memory trimming seems
14006 // to be good enough at this point that destroying
14007 // activities causes more harm than good.
14008 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14009 && app != mHomeProcess && app != mPreviousProcess) {
14010 // For these apps we will also finish their activities
14011 // to help them free memory.
14012 mMainStack.destroyActivitiesLocked(app, false, "trim");
14013 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014014 }
14015 }
14016 app.trimMemoryLevel = curLevel;
14017 step++;
14018 if (step >= factor) {
14019 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014020 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14021 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014022 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014023 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14024 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014025 break;
14026 }
14027 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014028 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014029 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014030 && app.thread != null) {
14031 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014032 app.thread.scheduleTrimMemory(
14033 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014034 } catch (RemoteException e) {
14035 }
14036 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014037 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014038 } else if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014039 && app.pendingUiClean) {
14040 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14041 && app.thread != null) {
14042 try {
14043 app.thread.scheduleTrimMemory(
14044 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14045 } catch (RemoteException e) {
14046 }
14047 }
14048 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14049 app.pendingUiClean = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014050 } else {
14051 app.trimMemoryLevel = 0;
14052 }
14053 }
14054 } else {
14055 final int N = mLruProcesses.size();
14056 for (i=0; i<N; i++) {
14057 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014058 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014059 && app.pendingUiClean) {
14060 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14061 && app.thread != null) {
14062 try {
14063 app.thread.scheduleTrimMemory(
14064 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14065 } catch (RemoteException e) {
14066 }
14067 }
14068 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14069 app.pendingUiClean = false;
14070 } else {
14071 app.trimMemoryLevel = 0;
14072 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014073 }
14074 }
14075
14076 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014077 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014079 }
14080
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014081 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082 synchronized (this) {
14083 int i;
14084
14085 // First remove any unused application processes whose package
14086 // has been removed.
14087 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14088 final ProcessRecord app = mRemovedProcesses.get(i);
14089 if (app.activities.size() == 0
14090 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014091 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014092 TAG, "Exiting empty application process "
14093 + app.processName + " ("
14094 + (app.thread != null ? app.thread.asBinder() : null)
14095 + ")\n");
14096 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014097 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14098 app.processName, app.setAdj, "empty");
14099 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014100 } else {
14101 try {
14102 app.thread.scheduleExit();
14103 } catch (Exception e) {
14104 // Ignore exceptions.
14105 }
14106 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014107 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014108 mRemovedProcesses.remove(i);
14109
14110 if (app.persistent) {
14111 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014112 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014113 }
14114 }
14115 }
14116 }
14117
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014118 // Now update the oom adj for all processes.
14119 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014120 }
14121 }
14122
14123 /** This method sends the specified signal to each of the persistent apps */
14124 public void signalPersistentProcesses(int sig) throws RemoteException {
14125 if (sig != Process.SIGNAL_USR1) {
14126 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14127 }
14128
14129 synchronized (this) {
14130 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14131 != PackageManager.PERMISSION_GRANTED) {
14132 throw new SecurityException("Requires permission "
14133 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14134 }
14135
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014136 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14137 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014138 if (r.thread != null && r.persistent) {
14139 Process.sendSignal(r.pid, sig);
14140 }
14141 }
14142 }
14143 }
14144
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014145 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14146 if (proc == null || proc == mProfileProc) {
14147 proc = mProfileProc;
14148 path = mProfileFile;
14149 profileType = mProfileType;
14150 clearProfilerLocked();
14151 }
14152 if (proc == null) {
14153 return;
14154 }
14155 try {
14156 proc.thread.profilerControl(false, path, null, profileType);
14157 } catch (RemoteException e) {
14158 throw new IllegalStateException("Process disappeared");
14159 }
14160 }
14161
14162 private void clearProfilerLocked() {
14163 if (mProfileFd != null) {
14164 try {
14165 mProfileFd.close();
14166 } catch (IOException e) {
14167 }
14168 }
14169 mProfileApp = null;
14170 mProfileProc = null;
14171 mProfileFile = null;
14172 mProfileType = 0;
14173 mAutoStopProfiler = false;
14174 }
14175
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014176 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014177 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014178
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014179 try {
14180 synchronized (this) {
14181 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14182 // its own permission.
14183 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14184 != PackageManager.PERMISSION_GRANTED) {
14185 throw new SecurityException("Requires permission "
14186 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014187 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014188
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014189 if (start && fd == null) {
14190 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014191 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014192
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014193 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014194 if (process != null) {
14195 try {
14196 int pid = Integer.parseInt(process);
14197 synchronized (mPidsSelfLocked) {
14198 proc = mPidsSelfLocked.get(pid);
14199 }
14200 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014201 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014202
14203 if (proc == null) {
14204 HashMap<String, SparseArray<ProcessRecord>> all
14205 = mProcessNames.getMap();
14206 SparseArray<ProcessRecord> procs = all.get(process);
14207 if (procs != null && procs.size() > 0) {
14208 proc = procs.valueAt(0);
14209 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014210 }
14211 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014212
14213 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014214 throw new IllegalArgumentException("Unknown process: " + process);
14215 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014216
14217 if (start) {
14218 stopProfilerLocked(null, null, 0);
14219 setProfileApp(proc.info, proc.processName, path, fd, false);
14220 mProfileProc = proc;
14221 mProfileType = profileType;
14222 try {
14223 fd = fd.dup();
14224 } catch (IOException e) {
14225 fd = null;
14226 }
14227 proc.thread.profilerControl(start, path, fd, profileType);
14228 fd = null;
14229 mProfileFd = null;
14230 } else {
14231 stopProfilerLocked(proc, path, profileType);
14232 if (fd != null) {
14233 try {
14234 fd.close();
14235 } catch (IOException e) {
14236 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014237 }
14238 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014239
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014240 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014241 }
14242 } catch (RemoteException e) {
14243 throw new IllegalStateException("Process disappeared");
14244 } finally {
14245 if (fd != null) {
14246 try {
14247 fd.close();
14248 } catch (IOException e) {
14249 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014250 }
14251 }
14252 }
Andy McFadden824c5102010-07-09 16:26:57 -070014253
14254 public boolean dumpHeap(String process, boolean managed,
14255 String path, ParcelFileDescriptor fd) throws RemoteException {
14256
14257 try {
14258 synchronized (this) {
14259 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14260 // its own permission (same as profileControl).
14261 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14262 != PackageManager.PERMISSION_GRANTED) {
14263 throw new SecurityException("Requires permission "
14264 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14265 }
14266
14267 if (fd == null) {
14268 throw new IllegalArgumentException("null fd");
14269 }
14270
14271 ProcessRecord proc = null;
14272 try {
14273 int pid = Integer.parseInt(process);
14274 synchronized (mPidsSelfLocked) {
14275 proc = mPidsSelfLocked.get(pid);
14276 }
14277 } catch (NumberFormatException e) {
14278 }
14279
14280 if (proc == null) {
14281 HashMap<String, SparseArray<ProcessRecord>> all
14282 = mProcessNames.getMap();
14283 SparseArray<ProcessRecord> procs = all.get(process);
14284 if (procs != null && procs.size() > 0) {
14285 proc = procs.valueAt(0);
14286 }
14287 }
14288
14289 if (proc == null || proc.thread == null) {
14290 throw new IllegalArgumentException("Unknown process: " + process);
14291 }
14292
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014293 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14294 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014295 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14296 throw new SecurityException("Process not debuggable: " + proc);
14297 }
14298 }
14299
14300 proc.thread.dumpHeap(managed, path, fd);
14301 fd = null;
14302 return true;
14303 }
14304 } catch (RemoteException e) {
14305 throw new IllegalStateException("Process disappeared");
14306 } finally {
14307 if (fd != null) {
14308 try {
14309 fd.close();
14310 } catch (IOException e) {
14311 }
14312 }
14313 }
14314 }
14315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014316 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14317 public void monitor() {
14318 synchronized (this) { }
14319 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014320
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014321 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014322 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14323 ProcessRecord processRecord = mLruProcesses.get(i);
14324 try {
14325 if (processRecord.thread != null) {
14326 processRecord.thread.setCoreSettings(settings);
14327 }
14328 } catch (RemoteException re) {
14329 /* ignore */
14330 }
14331 }
14332 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014333
14334 // Multi-user methods
14335
Amith Yamasani742a6712011-05-04 14:49:28 -070014336 private int mCurrentUserId;
14337 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14338
14339 public boolean switchUser(int userId) {
14340 final int callingUid = Binder.getCallingUid();
14341 if (callingUid != 0 && callingUid != Process.myUid()) {
14342 Slog.e(TAG, "Trying to switch user from unauthorized app");
14343 return false;
14344 }
14345 if (mCurrentUserId == userId)
14346 return true;
14347
14348 synchronized (this) {
14349 // Check if user is already logged in, otherwise check if user exists first before
14350 // adding to the list of logged in users.
14351 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14352 if (!userExists(userId)) {
14353 return false;
14354 }
14355 mLoggedInUsers.append(userId, userId);
14356 }
14357
14358 mCurrentUserId = userId;
14359 boolean haveActivities = mMainStack.switchUser(userId);
14360 if (!haveActivities) {
14361 startHomeActivityLocked(userId);
14362 }
14363 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014364 return true;
14365 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014366
14367 private boolean userExists(int userId) {
14368 try {
14369 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14370 for (UserInfo user : users) {
14371 if (user.id == userId) {
14372 return true;
14373 }
14374 }
14375 } catch (RemoteException re) {
14376 // Won't happen, in same process
14377 }
14378
14379 return false;
14380 }
14381
14382
14383 private int applyUserId(int uid, int userId) {
14384 return UserId.getUid(userId, uid);
14385 }
14386
14387 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014388 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014389 ApplicationInfo newInfo = new ApplicationInfo(info);
14390 newInfo.uid = applyUserId(info.uid, userId);
14391 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14392 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14393 + info.packageName;
14394 }
14395 return newInfo;
14396 }
14397
14398 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014399 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014400 || userId < 1) {
14401 return aInfo;
14402 }
14403
14404 ActivityInfo info = new ActivityInfo(aInfo);
14405 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14406 return info;
14407 }
14408
14409 static class ServiceMap {
14410
14411 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14412 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14413 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14414 mServicesByIntentPerUser = new SparseArray<
14415 HashMap<Intent.FilterComparison, ServiceRecord>>();
14416
14417 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14418 // TODO: Deal with global services
14419 if (DEBUG_MU)
14420 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14421 return getServices(callingUser).get(name);
14422 }
14423
14424 ServiceRecord getServiceByName(ComponentName name) {
14425 return getServiceByName(name, -1);
14426 }
14427
14428 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14429 // TODO: Deal with global services
14430 if (DEBUG_MU)
14431 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14432 return getServicesByIntent(callingUser).get(filter);
14433 }
14434
14435 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14436 return getServiceByIntent(filter, -1);
14437 }
14438
14439 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14440 // TODO: Deal with global services
14441 getServices(callingUser).put(name, value);
14442 }
14443
14444 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14445 ServiceRecord value) {
14446 // TODO: Deal with global services
14447 getServicesByIntent(callingUser).put(filter, value);
14448 }
14449
14450 void removeServiceByName(ComponentName name, int callingUser) {
14451 // TODO: Deal with global services
14452 ServiceRecord removed = getServices(callingUser).remove(name);
14453 if (DEBUG_MU)
14454 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14455 + " removed=" + removed);
14456 }
14457
14458 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14459 // TODO: Deal with global services
14460 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14461 if (DEBUG_MU)
14462 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14463 + " removed=" + removed);
14464 }
14465
14466 Collection<ServiceRecord> getAllServices(int callingUser) {
14467 // TODO: Deal with global services
14468 return getServices(callingUser).values();
14469 }
14470
14471 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14472 HashMap map = mServicesByNamePerUser.get(callingUser);
14473 if (map == null) {
14474 map = new HashMap<ComponentName, ServiceRecord>();
14475 mServicesByNamePerUser.put(callingUser, map);
14476 }
14477 return map;
14478 }
14479
14480 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14481 int callingUser) {
14482 HashMap map = mServicesByIntentPerUser.get(callingUser);
14483 if (map == null) {
14484 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14485 mServicesByIntentPerUser.put(callingUser, map);
14486 }
14487 return map;
14488 }
14489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014490}