blob: 0c5a8278c581608dfeb8c42bcda87e61da76200e [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
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
37import android.app.ActivityThread;
38import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070039import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020040import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070042import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.IApplicationThread;
44import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070045import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070046import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.IServiceConnection;
48import android.app.IThumbnailReceiver;
49import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070050import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070051import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070053import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080054import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020055import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080056import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080057import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070058import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070060import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.ContentResolver;
62import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020063import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.Intent;
65import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070066import android.content.IIntentReceiver;
67import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070068import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.pm.ActivityInfo;
70import android.content.pm.ApplicationInfo;
71import android.content.pm.ConfigurationInfo;
72import android.content.pm.IPackageDataObserver;
73import android.content.pm.IPackageManager;
74import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080075import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070077import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.ProviderInfo;
79import android.content.pm.ResolveInfo;
80import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070081import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070082import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040083import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.res.Configuration;
85import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070086import android.net.Proxy;
87import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.net.Uri;
89import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080091import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070092import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080093import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080095import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.FileUtils;
97import android.os.Handler;
98import android.os.IBinder;
99import android.os.IPermissionController;
100import android.os.Looper;
101import android.os.Message;
102import android.os.Parcel;
103import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700105import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.RemoteException;
107import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700108import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.SystemClock;
110import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700111import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700114import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800115import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.util.PrintWriterPrinter;
118import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700119import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700120import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.view.Gravity;
122import android.view.LayoutInflater;
123import android.view.View;
124import android.view.WindowManager;
125import android.view.WindowManagerPolicy;
126
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.BufferedInputStream;
128import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700129import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.DataInputStream;
131import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.File;
133import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700134import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200137import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800138import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700140import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.lang.IllegalStateException;
142import java.lang.ref.WeakReference;
143import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700144import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700145import java.util.Collections;
146import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147import java.util.HashMap;
148import java.util.HashSet;
149import java.util.Iterator;
150import java.util.List;
151import java.util.Locale;
152import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700153import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700154import java.util.concurrent.atomic.AtomicBoolean;
155import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700157public final class ActivityManagerService extends ActivityManagerNative
158 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700159 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400163 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG_SWITCH = localLOGV || false;
165 static final boolean DEBUG_TASKS = localLOGV || false;
166 static final boolean DEBUG_PAUSE = localLOGV || false;
167 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
168 static final boolean DEBUG_TRANSITION = localLOGV || false;
169 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800170 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700171 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700173 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_VISBILITY = localLOGV || false;
175 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700176 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800177 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700179 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700180 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700181 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700182 static final boolean DEBUG_POWER = localLOGV || false;
183 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700184 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 static final boolean VALIDATE_TOKENS = false;
186 static final boolean SHOW_ACTIVITY_START_TIME = true;
187
188 // Control over CPU and battery monitoring.
189 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
190 static final boolean MONITOR_CPU_USAGE = true;
191 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
192 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
193 static final boolean MONITOR_THREAD_CPU_USAGE = false;
194
Dianne Hackborn1655be42009-05-08 14:29:01 -0700195 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700196 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800198 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 // Maximum number of recent tasks that we can remember.
201 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700202
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700203 // Amount of time after a call to stopAppSwitches() during which we will
204 // prevent further untrusted switches from happening.
205 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
207 // How long we wait for a launched process to attach to the activity manager
208 // before we decide it's never going to come up for real.
209 static final int PROC_START_TIMEOUT = 10*1000;
210
Jeff Brown3f9dd282011-07-08 20:02:19 -0700211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real, when the process was
213 // started with a wrapper for instrumentation (such as Valgrind) because it
214 // could take much longer than usual.
215 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // How long to wait after going idle before forcing apps to GC.
218 static final int GC_TIMEOUT = 5*1000;
219
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700220 // The minimum amount of time between successive GC requests for a process.
221 static final int GC_MIN_INTERVAL = 60*1000;
222
Dianne Hackborn287952c2010-09-22 22:34:31 -0700223 // The rate at which we check for apps using excessive power -- 15 mins.
224 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
225
226 // The minimum sample duration we will allow before deciding we have
227 // enough data on wake locks to start killing things.
228 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on CPU usage to start killing things.
232 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800235 static final int BROADCAST_FG_TIMEOUT = 10*1000;
236 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 // How long we wait for a service to finish executing.
239 static final int SERVICE_TIMEOUT = 20*1000;
240
241 // How long a service needs to be running until restarting its process
242 // is no longer considered to be a relaunch of the service.
243 static final int SERVICE_RESTART_DURATION = 5*1000;
244
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700245 // How long a service needs to be running until it will start back at
246 // SERVICE_RESTART_DURATION after being killed.
247 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
248
249 // Multiplying factor to increase restart duration time by, for each time
250 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
251 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
252
253 // The minimum amount of time between restarting services that we allow.
254 // That is, when multiple services are restarting, we won't allow each
255 // to restart less than this amount of time from the last one.
256 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 // Maximum amount of time for there to be no activity on a service before
259 // we consider it non-essential and allow its process to go on the
260 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700261 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 // How long we wait until we timeout on key dispatching.
264 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 // How long we wait until we timeout on key dispatching during instrumentation.
267 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
268
Dan Egnor42471dd2010-01-07 17:25:22 -0800269 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270
271 static final String[] EMPTY_STRING_ARRAY = new String[0];
272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700273 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700274
275 private final boolean mHeadless;
276
Joe Onorato54a4a412011-11-02 20:50:08 -0700277 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
278 // default actuion automatically. Important for devices without direct input
279 // devices.
280 private boolean mShowDialogs = true;
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700283 * Description of a request to start a new activity, which has been held
284 * due to app switches being disabled.
285 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700286 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700287 ActivityRecord r;
288 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700289 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700290 }
291
292 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
293 = new ArrayList<PendingActivityLaunch>();
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800296 BroadcastQueue mFgBroadcastQueue;
297 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800298 // Convenient for easy iteration over the queues. Foreground is first
299 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800301
302 BroadcastQueue broadcastQueueForIntent(Intent intent) {
303 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
304 if (DEBUG_BACKGROUND_BROADCAST) {
305 Slog.i(TAG, "Broadcast intent " + intent + " on "
306 + (isFg ? "foreground" : "background")
307 + " queue");
308 }
309 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
310 }
311
312 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
313 for (BroadcastQueue queue : mBroadcastQueues) {
314 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
315 if (r != null) {
316 return r;
317 }
318 }
319 return null;
320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321
322 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 * Activity we have told the window manager to have key focus.
324 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700325 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * List of intents that were used to start the most recent tasks.
328 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700329 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
331 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700332 * Process management.
333 */
334 final ProcessList mProcessList = new ProcessList();
335
336 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 * All of the applications we currently have running organized by name.
338 * The keys are strings of the application package name (as
339 * returned by the package manager), and the keys are ApplicationRecord
340 * objects.
341 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700342 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343
344 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800345 * The currently running isolated processes.
346 */
347 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
348
349 /**
350 * Counter for assigning isolated process uids, to avoid frequently reusing the
351 * same ones.
352 */
353 int mNextIsolatedProcessUid = 0;
354
355 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700356 * The currently running heavy-weight process, if any.
357 */
358 ProcessRecord mHeavyWeightProcess = null;
359
360 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 * The last time that various processes have crashed.
362 */
363 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
364
365 /**
366 * Set of applications that we consider to be bad, and will reject
367 * incoming broadcasts from (which the user has no control over).
368 * Processes are added to this set when they have crashed twice within
369 * a minimum amount of time; they are removed from it when they are
370 * later restarted (hopefully due to some user action). The value is the
371 * time it was added to the list.
372 */
373 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
374
375 /**
376 * All of the processes we currently have running organized by pid.
377 * The keys are the pid running the application.
378 *
379 * <p>NOTE: This object is protected by its own lock, NOT the global
380 * activity manager lock!
381 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700382 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383
384 /**
385 * All of the processes that have been forced to be foreground. The key
386 * is the pid of the caller who requested it (we hold a death
387 * link on it).
388 */
389 abstract class ForegroundToken implements IBinder.DeathRecipient {
390 int pid;
391 IBinder token;
392 }
393 final SparseArray<ForegroundToken> mForegroundProcesses
394 = new SparseArray<ForegroundToken>();
395
396 /**
397 * List of records for processes that someone had tried to start before the
398 * system was ready. We don't start them at that point, but ensure they
399 * are started by the time booting is complete.
400 */
401 final ArrayList<ProcessRecord> mProcessesOnHold
402 = new ArrayList<ProcessRecord>();
403
404 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 * List of persistent applications that are in the process
406 * of being started.
407 */
408 final ArrayList<ProcessRecord> mPersistentStartingProcesses
409 = new ArrayList<ProcessRecord>();
410
411 /**
412 * Processes that are being forcibly torn down.
413 */
414 final ArrayList<ProcessRecord> mRemovedProcesses
415 = new ArrayList<ProcessRecord>();
416
417 /**
418 * List of running applications, sorted by recent usage.
419 * The first entry in the list is the least recently used.
420 * It contains ApplicationRecord objects. This list does NOT include
421 * any persistent application records (since we never want to exit them).
422 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800423 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 = new ArrayList<ProcessRecord>();
425
426 /**
427 * List of processes that should gc as soon as things are idle.
428 */
429 final ArrayList<ProcessRecord> mProcessesToGc
430 = new ArrayList<ProcessRecord>();
431
432 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800433 * This is the process holding what we currently consider to be
434 * the "home" activity.
435 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700436 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437
438 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700439 * This is the process holding the activity the user last visited that
440 * is in a different process from the one they are currently in.
441 */
442 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800443
444 /**
445 * The time at which the previous process was last visible.
446 */
447 long mPreviousProcessVisibleTime;
448
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700449 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400450 * Packages that the user has asked to have run in screen size
451 * compatibility mode instead of filling the screen.
452 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700453 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454
455 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 * Set of PendingResultRecord objects that are currently active.
457 */
458 final HashSet mPendingResultRecords = new HashSet();
459
460 /**
461 * Set of IntentSenderRecord objects that are currently active.
462 */
463 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
464 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
465
466 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800467 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700468 * already logged DropBox entries for. Guarded by itself. If
469 * something (rogue user app) forces this over
470 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
471 */
472 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
473 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
474
475 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700476 * Strict Mode background batched logging state.
477 *
478 * The string buffer is guarded by itself, and its lock is also
479 * used to determine if another batched write is already
480 * in-flight.
481 */
482 private final StringBuilder mStrictModeBuffer = new StringBuilder();
483
484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 * Keeps track of all IIntentReceivers that have been registered for
486 * broadcasts. Hash keys are the receiver IBinder, hash value is
487 * a ReceiverList.
488 */
489 final HashMap mRegisteredReceivers = new HashMap();
490
491 /**
492 * Resolver for broadcast intents to registered receivers.
493 * Holds BroadcastFilter (subclass of IntentFilter).
494 */
495 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
496 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
497 @Override
498 protected boolean allowFilterResult(
499 BroadcastFilter filter, List<BroadcastFilter> dest) {
500 IBinder target = filter.receiverList.receiver.asBinder();
501 for (int i=dest.size()-1; i>=0; i--) {
502 if (dest.get(i).receiverList.receiver.asBinder() == target) {
503 return false;
504 }
505 }
506 return true;
507 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700508
509 @Override
510 protected String packageForFilter(BroadcastFilter filter) {
511 return filter.packageName;
512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 };
514
515 /**
516 * State of all active sticky broadcasts. Keys are the action of the
517 * sticky Intent, values are an ArrayList of all broadcasted intents with
518 * that action (which should usually be one).
519 */
520 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
521 new HashMap<String, ArrayList<Intent>>();
522
Amith Yamasani742a6712011-05-04 14:49:28 -0700523 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
525 /**
526 * All currently bound service connections. Keys are the IBinder of
527 * the client's IServiceConnection.
528 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700529 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
530 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531
532 /**
533 * List of services that we have been asked to start,
534 * but haven't yet been able to. It is used to hold start requests
535 * while waiting for their corresponding application thread to get
536 * going.
537 */
538 final ArrayList<ServiceRecord> mPendingServices
539 = new ArrayList<ServiceRecord>();
540
541 /**
542 * List of services that are scheduled to restart following a crash.
543 */
544 final ArrayList<ServiceRecord> mRestartingServices
545 = new ArrayList<ServiceRecord>();
546
547 /**
548 * List of services that are in the process of being stopped.
549 */
550 final ArrayList<ServiceRecord> mStoppingServices
551 = new ArrayList<ServiceRecord>();
552
553 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700554 * Backup/restore process management
555 */
556 String mBackupAppName = null;
557 BackupRecord mBackupTarget = null;
558
559 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 * List of PendingThumbnailsRecord objects of clients who are still
561 * waiting to receive all of the thumbnails for a task.
562 */
563 final ArrayList mPendingThumbnails = new ArrayList();
564
565 /**
566 * List of HistoryRecord objects that have been finished and must
567 * still report back to a pending thumbnail receiver.
568 */
569 final ArrayList mCancelledThumbnails = new ArrayList();
570
Amith Yamasani742a6712011-05-04 14:49:28 -0700571 final ProviderMap mProviderMap = new ProviderMap();
572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 /**
574 * List of content providers who have clients waiting for them. The
575 * application is currently being launched and the provider will be
576 * removed from this list once it is published.
577 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700578 final ArrayList<ContentProviderRecord> mLaunchingProviders
579 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580
581 /**
582 * Global set of specific Uri permissions that have been granted.
583 */
584 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
585 = new SparseArray<HashMap<Uri, UriPermission>>();
586
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800587 CoreSettingsObserver mCoreSettingsObserver;
588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 /**
590 * Thread-local storage used to carry caller permissions over through
591 * indirect content-provider access.
592 * @see #ActivityManagerService.openContentUri()
593 */
594 private class Identity {
595 public int pid;
596 public int uid;
597
598 Identity(int _pid, int _uid) {
599 pid = _pid;
600 uid = _uid;
601 }
602 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
605
606 /**
607 * All information we have collected about the runtime performance of
608 * any user id that can impact battery performance.
609 */
610 final BatteryStatsService mBatteryStatsService;
611
612 /**
613 * information about component usage
614 */
615 final UsageStatsService mUsageStatsService;
616
617 /**
618 * Current configuration information. HistoryRecord objects are given
619 * a reference to this object to indicate which configuration they are
620 * currently running in, so this object must be kept immutable.
621 */
622 Configuration mConfiguration = new Configuration();
623
624 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800625 * Current sequencing integer of the configuration, for skipping old
626 * configurations.
627 */
628 int mConfigurationSeq = 0;
629
630 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700631 * Hardware-reported OpenGLES version.
632 */
633 final int GL_ES_VERSION;
634
635 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 * List of initialization arguments to pass to all processes when binding applications to them.
637 * For example, references to the commonly used services.
638 */
639 HashMap<String, IBinder> mAppBindArgs;
640
641 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700642 * Temporary to avoid allocations. Protected by main lock.
643 */
644 final StringBuilder mStringBuilder = new StringBuilder(256);
645
646 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 * Used to control how we initialize the service.
648 */
649 boolean mStartRunning = false;
650 ComponentName mTopComponent;
651 String mTopAction;
652 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700653 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 boolean mSystemReady = false;
655 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700656 boolean mWaitingUpdate = false;
657 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700658 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700659 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660
661 Context mContext;
662
663 int mFactoryTest;
664
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700665 boolean mCheckedForSetup;
666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700668 * The time at which we will allow normal application switches again,
669 * after a call to {@link #stopAppSwitches()}.
670 */
671 long mAppSwitchesAllowedTime;
672
673 /**
674 * This is set to true after the first switch after mAppSwitchesAllowedTime
675 * is set; any switches after that will clear the time.
676 */
677 boolean mDidAppSwitch;
678
679 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700680 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700681 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700682 long mLastPowerCheckRealtime;
683
684 /**
685 * Last time (in uptime) at which we checked for power usage.
686 */
687 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700688
689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 * Set while we are wanting to sleep, to prevent any
691 * activities from being started/resumed.
692 */
693 boolean mSleeping = false;
694
695 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700696 * Set if we are shutting down the system, similar to sleeping.
697 */
698 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
700 /**
701 * Task identifier that activities are currently being started
702 * in. Incremented each time a new task is created.
703 * todo: Replace this with a TokenSpace class that generates non-repeating
704 * integers that won't wrap.
705 */
706 int mCurTask = 1;
707
708 /**
709 * Current sequence id for oom_adj computation traversal.
710 */
711 int mAdjSeq = 0;
712
713 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700714 * Current sequence id for process LRU updating.
715 */
716 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717
718 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700719 * Keep track of the number of service processes we last found, to
720 * determine on the next iteration which should be B services.
721 */
722 int mNumServiceProcs = 0;
723 int mNewNumServiceProcs = 0;
724
725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 * System monitoring: number of processes that died since the last
727 * N procs were started.
728 */
729 int[] mProcDeaths = new int[20];
730
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700731 /**
732 * This is set if we had to do a delayed dexopt of an app before launching
733 * it, to increasing the ANR timeouts in that case.
734 */
735 boolean mDidDexOpt;
736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 String mDebugApp = null;
738 boolean mWaitForDebugger = false;
739 boolean mDebugTransient = false;
740 String mOrigDebugApp = null;
741 boolean mOrigWaitForDebugger = false;
742 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700743 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700744 String mProfileApp = null;
745 ProcessRecord mProfileProc = null;
746 String mProfileFile;
747 ParcelFileDescriptor mProfileFd;
748 int mProfileType = 0;
749 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800750 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
Jeff Sharkeya4620792011-05-20 15:29:23 -0700752 final RemoteCallbackList<IProcessObserver> mProcessObservers
753 = new RemoteCallbackList<IProcessObserver>();
754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 /**
756 * Callback of last caller to {@link #requestPss}.
757 */
758 Runnable mRequestPssCallback;
759
760 /**
761 * Remaining processes for which we are waiting results from the last
762 * call to {@link #requestPss}.
763 */
764 final ArrayList<ProcessRecord> mRequestPssList
765 = new ArrayList<ProcessRecord>();
766
767 /**
768 * Runtime statistics collection thread. This object's lock is used to
769 * protect all related state.
770 */
771 final Thread mProcessStatsThread;
772
773 /**
774 * Used to collect process stats when showing not responding dialog.
775 * Protected by mProcessStatsThread.
776 */
777 final ProcessStats mProcessStats = new ProcessStats(
778 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700779 final AtomicLong mLastCpuTime = new AtomicLong(0);
780 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 long mLastWriteTime = 0;
783
784 /**
785 * Set to true after the system has finished booting.
786 */
787 boolean mBooted = false;
788
Dianne Hackborn7d608422011-08-07 16:24:18 -0700789 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700790 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791
792 WindowManagerService mWindowManager;
793
794 static ActivityManagerService mSelf;
795 static ActivityThread mSystemThread;
796
797 private final class AppDeathRecipient implements IBinder.DeathRecipient {
798 final ProcessRecord mApp;
799 final int mPid;
800 final IApplicationThread mAppThread;
801
802 AppDeathRecipient(ProcessRecord app, int pid,
803 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800804 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 TAG, "New death recipient " + this
806 + " for thread " + thread.asBinder());
807 mApp = app;
808 mPid = pid;
809 mAppThread = thread;
810 }
811
812 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800813 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 TAG, "Death received in " + this
815 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 synchronized(ActivityManagerService.this) {
817 appDiedLocked(mApp, mPid, mAppThread);
818 }
819 }
820 }
821
822 static final int SHOW_ERROR_MSG = 1;
823 static final int SHOW_NOT_RESPONDING_MSG = 2;
824 static final int SHOW_FACTORY_ERROR_MSG = 3;
825 static final int UPDATE_CONFIGURATION_MSG = 4;
826 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
827 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 static final int SERVICE_TIMEOUT_MSG = 12;
829 static final int UPDATE_TIME_ZONE = 13;
830 static final int SHOW_UID_ERROR_MSG = 14;
831 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700833 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700834 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800835 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700836 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
837 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700838 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700839 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700840 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700841 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700842 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700843 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
844 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700845 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800847 static final int FIRST_ACTIVITY_STACK_MSG = 100;
848 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
849 static final int FIRST_COMPAT_MODE_MSG = 300;
850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700852 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700853 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854
855 final Handler mHandler = new Handler() {
856 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800857 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 //}
859
860 public void handleMessage(Message msg) {
861 switch (msg.what) {
862 case SHOW_ERROR_MSG: {
863 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 synchronized (ActivityManagerService.this) {
865 ProcessRecord proc = (ProcessRecord)data.get("app");
866 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 return;
869 }
870 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700871 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800872 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 d.show();
874 proc.crashDialog = d;
875 } else {
876 // The device is asleep, so just pretend that the user
877 // saw a crash dialog and hit "force quit".
878 res.set(0);
879 }
880 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700881
882 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 } break;
884 case SHOW_NOT_RESPONDING_MSG: {
885 synchronized (ActivityManagerService.this) {
886 HashMap data = (HashMap) msg.obj;
887 ProcessRecord proc = (ProcessRecord)data.get("app");
888 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 return;
891 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800892
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700893 Intent intent = new Intent("android.intent.action.ANR");
894 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800895 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
896 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700897 }
898 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800899 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700900 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700903 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 d.show();
905 proc.anrDialog = d;
906 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700907
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700908 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700910 case SHOW_STRICT_MODE_VIOLATION_MSG: {
911 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
912 synchronized (ActivityManagerService.this) {
913 ProcessRecord proc = (ProcessRecord) data.get("app");
914 if (proc == null) {
915 Slog.e(TAG, "App not found when showing strict mode dialog.");
916 break;
917 }
918 if (proc.crashDialog != null) {
919 Slog.e(TAG, "App already has strict mode dialog: " + proc);
920 return;
921 }
922 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700923 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700924 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
925 d.show();
926 proc.crashDialog = d;
927 } else {
928 // The device is asleep, so just pretend that the user
929 // saw a crash dialog and hit "force quit".
930 res.set(0);
931 }
932 }
933 ensureBootCompleted();
934 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 case SHOW_FACTORY_ERROR_MSG: {
936 Dialog d = new FactoryErrorDialog(
937 mContext, msg.getData().getCharSequence("msg"));
938 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700939 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 } break;
941 case UPDATE_CONFIGURATION_MSG: {
942 final ContentResolver resolver = mContext.getContentResolver();
943 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
944 } break;
945 case GC_BACKGROUND_PROCESSES_MSG: {
946 synchronized (ActivityManagerService.this) {
947 performAppGcsIfAppropriateLocked();
948 }
949 } break;
950 case WAIT_FOR_DEBUGGER_MSG: {
951 synchronized (ActivityManagerService.this) {
952 ProcessRecord app = (ProcessRecord)msg.obj;
953 if (msg.arg1 != 0) {
954 if (!app.waitedForDebugger) {
955 Dialog d = new AppWaitingForDebuggerDialog(
956 ActivityManagerService.this,
957 mContext, app);
958 app.waitDialog = d;
959 app.waitedForDebugger = true;
960 d.show();
961 }
962 } else {
963 if (app.waitDialog != null) {
964 app.waitDialog.dismiss();
965 app.waitDialog = null;
966 }
967 }
968 }
969 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700971 if (mDidDexOpt) {
972 mDidDexOpt = false;
973 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
974 nmsg.obj = msg.obj;
975 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
976 return;
977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 serviceTimeout((ProcessRecord)msg.obj);
979 } break;
980 case UPDATE_TIME_ZONE: {
981 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800982 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
983 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 if (r.thread != null) {
985 try {
986 r.thread.updateTimeZone();
987 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800988 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
990 }
991 }
992 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700993 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700994 case CLEAR_DNS_CACHE: {
995 synchronized (ActivityManagerService.this) {
996 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
997 ProcessRecord r = mLruProcesses.get(i);
998 if (r.thread != null) {
999 try {
1000 r.thread.clearDnsCache();
1001 } catch (RemoteException ex) {
1002 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1003 }
1004 }
1005 }
1006 }
1007 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001008 case UPDATE_HTTP_PROXY: {
1009 ProxyProperties proxy = (ProxyProperties)msg.obj;
1010 String host = "";
1011 String port = "";
1012 String exclList = "";
1013 if (proxy != null) {
1014 host = proxy.getHost();
1015 port = Integer.toString(proxy.getPort());
1016 exclList = proxy.getExclusionList();
1017 }
1018 synchronized (ActivityManagerService.this) {
1019 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1020 ProcessRecord r = mLruProcesses.get(i);
1021 if (r.thread != null) {
1022 try {
1023 r.thread.setHttpProxy(host, port, exclList);
1024 } catch (RemoteException ex) {
1025 Slog.w(TAG, "Failed to update http proxy for: " +
1026 r.info.processName);
1027 }
1028 }
1029 }
1030 }
1031 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001033 String title = "System UIDs Inconsistent";
1034 String text = "UIDs on the system are inconsistent, you need to wipe your"
1035 + " data partition or your device will be unstable.";
1036 Log.e(TAG, title + ": " + text);
1037 if (mShowDialogs) {
1038 // XXX This is a temporary dialog, no need to localize.
1039 AlertDialog d = new BaseErrorDialog(mContext);
1040 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1041 d.setCancelable(false);
1042 d.setTitle(title);
1043 d.setMessage(text);
1044 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1045 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1046 mUidAlert = d;
1047 d.show();
1048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 } break;
1050 case IM_FEELING_LUCKY_MSG: {
1051 if (mUidAlert != null) {
1052 mUidAlert.dismiss();
1053 mUidAlert = null;
1054 }
1055 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001057 if (mDidDexOpt) {
1058 mDidDexOpt = false;
1059 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1060 nmsg.obj = msg.obj;
1061 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1062 return;
1063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 ProcessRecord app = (ProcessRecord)msg.obj;
1065 synchronized (ActivityManagerService.this) {
1066 processStartTimedOutLocked(app);
1067 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001068 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001069 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1070 synchronized (ActivityManagerService.this) {
1071 doPendingActivityLaunchesLocked(true);
1072 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001073 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001074 case KILL_APPLICATION_MSG: {
1075 synchronized (ActivityManagerService.this) {
1076 int uid = msg.arg1;
1077 boolean restart = (msg.arg2 == 1);
1078 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001079 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001080 }
1081 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001082 case FINALIZE_PENDING_INTENT_MSG: {
1083 ((PendingIntentRecord)msg.obj).completeFinalize();
1084 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001085 case POST_HEAVY_NOTIFICATION_MSG: {
1086 INotificationManager inm = NotificationManager.getService();
1087 if (inm == null) {
1088 return;
1089 }
1090
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001091 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001092 ProcessRecord process = root.app;
1093 if (process == null) {
1094 return;
1095 }
1096
1097 try {
1098 Context context = mContext.createPackageContext(process.info.packageName, 0);
1099 String text = mContext.getString(R.string.heavy_weight_notification,
1100 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1101 Notification notification = new Notification();
1102 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1103 notification.when = 0;
1104 notification.flags = Notification.FLAG_ONGOING_EVENT;
1105 notification.tickerText = text;
1106 notification.defaults = 0; // please be quiet
1107 notification.sound = null;
1108 notification.vibrate = null;
1109 notification.setLatestEventInfo(context, text,
1110 mContext.getText(R.string.heavy_weight_notification_detail),
1111 PendingIntent.getActivity(mContext, 0, root.intent,
1112 PendingIntent.FLAG_CANCEL_CURRENT));
1113
1114 try {
1115 int[] outId = new int[1];
1116 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1117 notification, outId);
1118 } catch (RuntimeException e) {
1119 Slog.w(ActivityManagerService.TAG,
1120 "Error showing notification for heavy-weight app", e);
1121 } catch (RemoteException e) {
1122 }
1123 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001124 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001125 }
1126 } break;
1127 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1128 INotificationManager inm = NotificationManager.getService();
1129 if (inm == null) {
1130 return;
1131 }
1132 try {
1133 inm.cancelNotification("android",
1134 R.string.heavy_weight_notification);
1135 } catch (RuntimeException e) {
1136 Slog.w(ActivityManagerService.TAG,
1137 "Error canceling notification for service", e);
1138 } catch (RemoteException e) {
1139 }
1140 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001141 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1142 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001143 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001144 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001145 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1146 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001147 }
1148 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001149 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1150 synchronized (ActivityManagerService.this) {
1151 ActivityRecord ar = (ActivityRecord)msg.obj;
1152 if (mCompatModeDialog != null) {
1153 if (mCompatModeDialog.mAppInfo.packageName.equals(
1154 ar.info.applicationInfo.packageName)) {
1155 return;
1156 }
1157 mCompatModeDialog.dismiss();
1158 mCompatModeDialog = null;
1159 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001160 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001161 if (mCompatModePackages.getPackageAskCompatModeLocked(
1162 ar.packageName)) {
1163 int mode = mCompatModePackages.computeCompatModeLocked(
1164 ar.info.applicationInfo);
1165 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1166 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1167 mCompatModeDialog = new CompatModeDialog(
1168 ActivityManagerService.this, mContext,
1169 ar.info.applicationInfo);
1170 mCompatModeDialog.show();
1171 }
1172 }
1173 }
1174 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001175 break;
1176 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001177 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001178 final int pid = msg.arg1;
1179 final int uid = msg.arg2;
1180 final boolean foregroundActivities = (Boolean) msg.obj;
1181 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001182 break;
1183 }
1184 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001185 final int pid = msg.arg1;
1186 final int uid = msg.arg2;
1187 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001188 break;
1189 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001190 case REPORT_MEM_USAGE: {
1191 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1192 if (!isDebuggable) {
1193 return;
1194 }
1195 synchronized (ActivityManagerService.this) {
1196 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001197 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1198 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001199 // avoid spamming.
1200 return;
1201 }
1202 mLastMemUsageReportTime = now;
1203 }
1204 Thread thread = new Thread() {
1205 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001206 StringBuilder dropBuilder = new StringBuilder(1024);
1207 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001208 StringWriter oomSw = new StringWriter();
1209 PrintWriter oomPw = new PrintWriter(oomSw);
1210 StringWriter catSw = new StringWriter();
1211 PrintWriter catPw = new PrintWriter(catSw);
1212 String[] emptyArgs = new String[] { };
1213 StringBuilder tag = new StringBuilder(128);
1214 StringBuilder stack = new StringBuilder(128);
1215 tag.append("Low on memory -- ");
1216 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1217 tag, stack);
1218 dropBuilder.append(stack);
1219 dropBuilder.append('\n');
1220 dropBuilder.append('\n');
1221 String oomString = oomSw.toString();
1222 dropBuilder.append(oomString);
1223 dropBuilder.append('\n');
1224 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001225 try {
1226 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1227 "procrank", });
1228 final InputStreamReader converter = new InputStreamReader(
1229 proc.getInputStream());
1230 BufferedReader in = new BufferedReader(converter);
1231 String line;
1232 while (true) {
1233 line = in.readLine();
1234 if (line == null) {
1235 break;
1236 }
1237 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001238 logBuilder.append(line);
1239 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001240 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001241 dropBuilder.append(line);
1242 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001243 }
1244 converter.close();
1245 } catch (IOException e) {
1246 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001247 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001248 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001249 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001250 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001251 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001252 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001253 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001254 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001255 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001256 addErrorToDropBox("lowmem", null, "system_server", null,
1257 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001259 synchronized (ActivityManagerService.this) {
1260 long now = SystemClock.uptimeMillis();
1261 if (mLastMemUsageReportTime < now) {
1262 mLastMemUsageReportTime = now;
1263 }
1264 }
1265 }
1266 };
1267 thread.start();
1268 break;
1269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271 }
1272 };
1273
1274 public static void setSystemProcess() {
1275 try {
1276 ActivityManagerService m = mSelf;
1277
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001278 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001280 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001281 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 if (MONITOR_CPU_USAGE) {
1283 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 ServiceManager.addService("permission", new PermissionController(m));
1286
1287 ApplicationInfo info =
1288 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001289 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001290 mSystemThread.installSystemApplicationInfo(info);
1291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 synchronized (mSelf) {
1293 ProcessRecord app = mSelf.newProcessRecordLocked(
1294 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001295 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001297 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001298 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001299 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 synchronized (mSelf.mPidsSelfLocked) {
1301 mSelf.mPidsSelfLocked.put(app.pid, app);
1302 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001303 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305 } catch (PackageManager.NameNotFoundException e) {
1306 throw new RuntimeException(
1307 "Unable to find android system package", e);
1308 }
1309 }
1310
1311 public void setWindowManager(WindowManagerService wm) {
1312 mWindowManager = wm;
1313 }
1314
1315 public static final Context main(int factoryTest) {
1316 AThread thr = new AThread();
1317 thr.start();
1318
1319 synchronized (thr) {
1320 while (thr.mService == null) {
1321 try {
1322 thr.wait();
1323 } catch (InterruptedException e) {
1324 }
1325 }
1326 }
1327
1328 ActivityManagerService m = thr.mService;
1329 mSelf = m;
1330 ActivityThread at = ActivityThread.systemMain();
1331 mSystemThread = at;
1332 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001333 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 m.mContext = context;
1335 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001336 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337
1338 m.mBatteryStatsService.publish(context);
1339 m.mUsageStatsService.publish(context);
1340
1341 synchronized (thr) {
1342 thr.mReady = true;
1343 thr.notifyAll();
1344 }
1345
1346 m.startRunning(null, null, null, null);
1347
1348 return context;
1349 }
1350
1351 public static ActivityManagerService self() {
1352 return mSelf;
1353 }
1354
1355 static class AThread extends Thread {
1356 ActivityManagerService mService;
1357 boolean mReady = false;
1358
1359 public AThread() {
1360 super("ActivityManager");
1361 }
1362
1363 public void run() {
1364 Looper.prepare();
1365
1366 android.os.Process.setThreadPriority(
1367 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001368 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369
1370 ActivityManagerService m = new ActivityManagerService();
1371
1372 synchronized (this) {
1373 mService = m;
1374 notifyAll();
1375 }
1376
1377 synchronized (this) {
1378 while (!mReady) {
1379 try {
1380 wait();
1381 } catch (InterruptedException e) {
1382 }
1383 }
1384 }
1385
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001386 // For debug builds, log event loop stalls to dropbox for analysis.
1387 if (StrictMode.conditionallyEnableDebugLogging()) {
1388 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1389 }
1390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 Looper.loop();
1392 }
1393 }
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 static class MemBinder extends Binder {
1396 ActivityManagerService mActivityManagerService;
1397 MemBinder(ActivityManagerService activityManagerService) {
1398 mActivityManagerService = activityManagerService;
1399 }
1400
1401 @Override
1402 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001403 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1404 != PackageManager.PERMISSION_GRANTED) {
1405 pw.println("Permission Denial: can't dump meminfo from from pid="
1406 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1407 + " without permission " + android.Manifest.permission.DUMP);
1408 return;
1409 }
1410
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001411 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001412 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
1414 }
1415
Chet Haase9c1e23b2011-03-24 10:51:31 -07001416 static class GraphicsBinder extends Binder {
1417 ActivityManagerService mActivityManagerService;
1418 GraphicsBinder(ActivityManagerService activityManagerService) {
1419 mActivityManagerService = activityManagerService;
1420 }
1421
1422 @Override
1423 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001424 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1425 != PackageManager.PERMISSION_GRANTED) {
1426 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1427 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1428 + " without permission " + android.Manifest.permission.DUMP);
1429 return;
1430 }
1431
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001432 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001433 }
1434 }
1435
Jeff Brown6754ba22011-12-14 20:20:01 -08001436 static class DbBinder extends Binder {
1437 ActivityManagerService mActivityManagerService;
1438 DbBinder(ActivityManagerService activityManagerService) {
1439 mActivityManagerService = activityManagerService;
1440 }
1441
1442 @Override
1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1445 != PackageManager.PERMISSION_GRANTED) {
1446 pw.println("Permission Denial: can't dump dbinfo from from pid="
1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1448 + " without permission " + android.Manifest.permission.DUMP);
1449 return;
1450 }
1451
1452 mActivityManagerService.dumpDbInfo(fd, pw, args);
1453 }
1454 }
1455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 static class CpuBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 CpuBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001473 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1474 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1475 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477 }
1478 }
1479
1480 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001481 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001482
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001483 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1484 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1485 mBroadcastQueues[0] = mFgBroadcastQueue;
1486 mBroadcastQueues[1] = mBgBroadcastQueue;
1487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 File dataDir = Environment.getDataDirectory();
1489 File systemDir = new File(dataDir, "system");
1490 systemDir.mkdirs();
1491 mBatteryStatsService = new BatteryStatsService(new File(
1492 systemDir, "batterystats.bin").toString());
1493 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001494 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001495 mOnBattery = DEBUG_POWER ? true
1496 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001497 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001499 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001500 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001501 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
Jack Palevichb90d28c2009-07-22 15:35:24 -07001503 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1504 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1505
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001506 mConfiguration.setToDefaults();
1507 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001508 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 mProcessStats.init();
1510
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001511 mCompatModePackages = new CompatModePackages(this, systemDir);
1512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 // Add ourself to the Watchdog monitors.
1514 Watchdog.getInstance().addMonitor(this);
1515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 mProcessStatsThread = new Thread("ProcessStats") {
1517 public void run() {
1518 while (true) {
1519 try {
1520 try {
1521 synchronized(this) {
1522 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001523 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 // + ", write delay=" + nextWriteDelay);
1527 if (nextWriteDelay < nextCpuDelay) {
1528 nextCpuDelay = nextWriteDelay;
1529 }
1530 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001531 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 this.wait(nextCpuDelay);
1533 }
1534 }
1535 } catch (InterruptedException e) {
1536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 updateCpuStatsNow();
1538 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001539 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 }
1542 }
1543 };
1544 mProcessStatsThread.start();
1545 }
1546
1547 @Override
1548 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1549 throws RemoteException {
1550 try {
1551 return super.onTransact(code, data, reply, flags);
1552 } catch (RuntimeException e) {
1553 // The activity manager only throws security exceptions, so let's
1554 // log all others.
1555 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001556 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558 throw e;
1559 }
1560 }
1561
1562 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001563 final long now = SystemClock.uptimeMillis();
1564 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1565 return;
1566 }
1567 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1568 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 mProcessStatsThread.notify();
1570 }
1571 }
1572 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 void updateCpuStatsNow() {
1575 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001576 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 final long now = SystemClock.uptimeMillis();
1578 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001581 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1582 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 haveNewCpuStats = true;
1584 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001585 //Slog.i(TAG, mProcessStats.printCurrentState());
1586 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 // + mProcessStats.getTotalCpuPercent() + "%");
1588
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 if ("true".equals(SystemProperties.get("events.cpu"))) {
1591 int user = mProcessStats.getLastUserTime();
1592 int system = mProcessStats.getLastSystemTime();
1593 int iowait = mProcessStats.getLastIoWaitTime();
1594 int irq = mProcessStats.getLastIrqTime();
1595 int softIrq = mProcessStats.getLastSoftIrqTime();
1596 int idle = mProcessStats.getLastIdleTime();
1597
1598 int total = user + system + iowait + irq + softIrq + idle;
1599 if (total == 0) total = 1;
1600
Doug Zongker2bec3d42009-12-04 12:52:44 -08001601 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 ((user+system+iowait+irq+softIrq) * 100) / total,
1603 (user * 100) / total,
1604 (system * 100) / total,
1605 (iowait * 100) / total,
1606 (irq * 100) / total,
1607 (softIrq * 100) / total);
1608 }
1609 }
1610
Amith Yamasanie43530a2009-08-21 13:11:37 -07001611 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001612 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001613 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 synchronized(mPidsSelfLocked) {
1615 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001616 if (mOnBattery) {
1617 int perc = bstats.startAddingCpuLocked();
1618 int totalUTime = 0;
1619 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001620 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001622 ProcessStats.Stats st = mProcessStats.getStats(i);
1623 if (!st.working) {
1624 continue;
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001627 int otherUTime = (st.rel_utime*perc)/100;
1628 int otherSTime = (st.rel_stime*perc)/100;
1629 totalUTime += otherUTime;
1630 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 if (pr != null) {
1632 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001633 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1634 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001635 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001636 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001637 } else {
1638 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001639 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001640 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001641 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1642 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001643 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001647 bstats.finishAddingCpuLocked(perc, totalUTime,
1648 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 }
1651 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1654 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001655 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657 }
1658 }
1659 }
1660
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 @Override
1662 public void batteryNeedsCpuUpdate() {
1663 updateCpuStatsNow();
1664 }
1665
1666 @Override
1667 public void batteryPowerChanged(boolean onBattery) {
1668 // When plugging in, update the CPU stats first before changing
1669 // the plug state.
1670 updateCpuStatsNow();
1671 synchronized (this) {
1672 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001673 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001674 }
1675 }
1676 }
1677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 /**
1679 * Initialize the application bind args. These are passed to each
1680 * process when the bindApplication() IPC is sent to the process. They're
1681 * lazily setup to make sure the services are running when they're asked for.
1682 */
1683 private HashMap<String, IBinder> getCommonServicesLocked() {
1684 if (mAppBindArgs == null) {
1685 mAppBindArgs = new HashMap<String, IBinder>();
1686
1687 // Setup the application init args
1688 mAppBindArgs.put("package", ServiceManager.getService("package"));
1689 mAppBindArgs.put("window", ServiceManager.getService("window"));
1690 mAppBindArgs.put(Context.ALARM_SERVICE,
1691 ServiceManager.getService(Context.ALARM_SERVICE));
1692 }
1693 return mAppBindArgs;
1694 }
1695
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001696 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 if (mFocusedActivity != r) {
1698 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001699 if (r != null) {
1700 mWindowManager.setFocusedApp(r.appToken, true);
1701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703 }
1704
Dianne Hackborn906497c2010-05-10 15:57:38 -07001705 private final void updateLruProcessInternalLocked(ProcessRecord app,
1706 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001708 int lrui = mLruProcesses.indexOf(app);
1709 if (lrui >= 0) mLruProcesses.remove(lrui);
1710
1711 int i = mLruProcesses.size()-1;
1712 int skipTop = 0;
1713
Dianne Hackborn906497c2010-05-10 15:57:38 -07001714 app.lruSeq = mLruSeq;
1715
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001716 // compute the new weight for this process.
1717 if (updateActivityTime) {
1718 app.lastActivityTime = SystemClock.uptimeMillis();
1719 }
1720 if (app.activities.size() > 0) {
1721 // If this process has activities, we more strongly want to keep
1722 // it around.
1723 app.lruWeight = app.lastActivityTime;
1724 } else if (app.pubProviders.size() > 0) {
1725 // If this process contains content providers, we want to keep
1726 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001727 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001729 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001730 } else {
1731 // If this process doesn't have activities, we less strongly
1732 // want to keep it around, and generally want to avoid getting
1733 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001734 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001735 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001736 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001737 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001738
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001739 while (i >= 0) {
1740 ProcessRecord p = mLruProcesses.get(i);
1741 // If this app shouldn't be in front of the first N background
1742 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001743 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001744 skipTop--;
1745 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001746 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001747 mLruProcesses.add(i+1, app);
1748 break;
1749 }
1750 i--;
1751 }
1752 if (i < 0) {
1753 mLruProcesses.add(0, app);
1754 }
1755
Dianne Hackborn906497c2010-05-10 15:57:38 -07001756 // If the app is currently using a content provider or service,
1757 // bump those processes as well.
1758 if (app.connections.size() > 0) {
1759 for (ConnectionRecord cr : app.connections) {
1760 if (cr.binding != null && cr.binding.service != null
1761 && cr.binding.service.app != null
1762 && cr.binding.service.app.lruSeq != mLruSeq) {
1763 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1764 updateActivityTime, i+1);
1765 }
1766 }
1767 }
1768 if (app.conProviders.size() > 0) {
1769 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001770 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1771 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001772 updateActivityTime, i+1);
1773 }
1774 }
1775 }
1776
Joe Onorato8a9b2202010-02-26 18:56:32 -08001777 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 if (oomAdj) {
1779 updateOomAdjLocked();
1780 }
1781 }
1782
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001784 boolean oomAdj, boolean updateActivityTime) {
1785 mLruSeq++;
1786 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1787 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001788
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001789 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 String processName, int uid) {
1791 if (uid == Process.SYSTEM_UID) {
1792 // The system gets to run in any process. If there are multiple
1793 // processes with the same uid, just pick the first (this
1794 // should never happen).
1795 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1796 processName);
1797 return procs != null ? procs.valueAt(0) : null;
1798 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001799 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 ProcessRecord proc = mProcessNames.get(processName, uid);
1801 return proc;
1802 }
1803
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001805 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001806 try {
1807 if (pm.performDexOpt(packageName)) {
1808 mDidDexOpt = true;
1809 }
1810 } catch (RemoteException e) {
1811 }
1812 }
1813
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001814 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 int transit = mWindowManager.getPendingAppTransition();
1816 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1817 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1818 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1819 }
1820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001823 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1824 boolean isolated) {
1825 ProcessRecord app;
1826 if (!isolated) {
1827 app = getProcessRecordLocked(processName, info.uid);
1828 } else {
1829 // If this is an isolated process, it can't re-use an existing process.
1830 app = null;
1831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 // We don't have to do anything more if:
1833 // (1) There is an existing application record; and
1834 // (2) The caller doesn't think it is dead, OR there is no thread
1835 // object attached to it so we know it couldn't have crashed; and
1836 // (3) There is a pid assigned to it, so it is either starting or
1837 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001838 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 + " app=" + app + " knownToBeDead=" + knownToBeDead
1840 + " thread=" + (app != null ? app.thread : null)
1841 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001842 if (app != null && app.pid > 0) {
1843 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001844 // We already have the app running, or are waiting for it to
1845 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001846 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001847 // If this is a new package in the process, add the package to the list
1848 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001849 return app;
1850 } else {
1851 // An application record is attached to a previous process,
1852 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001853 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001854 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 String hostingNameStr = hostingName != null
1859 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001860
1861 if (!isolated) {
1862 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1863 // If we are in the background, then check to see if this process
1864 // is bad. If so, we will just silently fail.
1865 if (mBadProcesses.get(info.processName, info.uid) != null) {
1866 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1867 + "/" + info.processName);
1868 return null;
1869 }
1870 } else {
1871 // When the user is explicitly starting a process, then clear its
1872 // crash count so that we won't make it bad until they see at
1873 // least one crash dialog again, and make the process good again
1874 // if it had been bad.
1875 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001876 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001877 mProcessCrashTimes.remove(info.processName, info.uid);
1878 if (mBadProcesses.get(info.processName, info.uid) != null) {
1879 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1880 info.processName);
1881 mBadProcesses.remove(info.processName, info.uid);
1882 if (app != null) {
1883 app.bad = false;
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 }
1887 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001890 app = newProcessRecordLocked(null, info, processName, isolated);
1891 if (app == null) {
1892 Slog.w(TAG, "Failed making new process record for "
1893 + processName + "/" + info.uid + " isolated=" + isolated);
1894 return null;
1895 }
1896 mProcessNames.put(processName, app.uid, app);
1897 if (isolated) {
1898 mIsolatedProcesses.put(app.uid, app);
1899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 } else {
1901 // If this is a new package in the process, add the package to the list
1902 app.addPackage(info.packageName);
1903 }
1904
1905 // If the system is not ready yet, then hold off on starting this
1906 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001907 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001908 && !isAllowedWhileBooting(info)
1909 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 if (!mProcessesOnHold.contains(app)) {
1911 mProcessesOnHold.add(app);
1912 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001913 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 return app;
1915 }
1916
1917 startProcessLocked(app, hostingType, hostingNameStr);
1918 return (app.pid != 0) ? app : null;
1919 }
1920
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001921 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1922 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1923 }
1924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 private final void startProcessLocked(ProcessRecord app,
1926 String hostingType, String hostingNameStr) {
1927 if (app.pid > 0 && app.pid != MY_PID) {
1928 synchronized (mPidsSelfLocked) {
1929 mPidsSelfLocked.remove(app.pid);
1930 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1931 }
1932 app.pid = 0;
1933 }
1934
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001935 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1936 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 mProcessesOnHold.remove(app);
1938
1939 updateCpuStats();
1940
1941 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1942 mProcDeaths[0] = 0;
1943
1944 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001945 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001948 if (!app.isolated) {
1949 try {
1950 gids = mContext.getPackageManager().getPackageGids(
1951 app.info.packageName);
1952 } catch (PackageManager.NameNotFoundException e) {
1953 Slog.w(TAG, "Unable to retrieve gids", e);
1954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
1956 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1957 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1958 && mTopComponent != null
1959 && app.processName.equals(mTopComponent.getPackageName())) {
1960 uid = 0;
1961 }
1962 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1963 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1964 uid = 0;
1965 }
1966 }
1967 int debugFlags = 0;
1968 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1969 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001970 // Also turn on CheckJNI for debuggable apps. It's quite
1971 // awkward to turn on otherwise.
1972 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001974 // Run the app in safe mode if its manifest requests so or the
1975 // system is booted in safe mode.
1976 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1977 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001978 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1981 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1982 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001983 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1984 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 if ("1".equals(SystemProperties.get("debug.assert"))) {
1987 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1988 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001989
1990 // Start the process. It will either succeed and return a result containing
1991 // the PID of the new process, or else throw a RuntimeException.
1992 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001993 app.processName, uid, uid, gids, debugFlags,
1994 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1997 synchronized (bs) {
1998 if (bs.isOnBattery()) {
1999 app.batteryStats.incStartsLocked();
2000 }
2001 }
2002
Jeff Brown3f9dd282011-07-08 20:02:19 -07002003 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 app.processName, hostingType,
2005 hostingNameStr != null ? hostingNameStr : "");
2006
2007 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002008 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002011 StringBuilder buf = mStringBuilder;
2012 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 buf.append("Start proc ");
2014 buf.append(app.processName);
2015 buf.append(" for ");
2016 buf.append(hostingType);
2017 if (hostingNameStr != null) {
2018 buf.append(" ");
2019 buf.append(hostingNameStr);
2020 }
2021 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002022 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 buf.append(" uid=");
2024 buf.append(uid);
2025 buf.append(" gids={");
2026 if (gids != null) {
2027 for (int gi=0; gi<gids.length; gi++) {
2028 if (gi != 0) buf.append(", ");
2029 buf.append(gids[gi]);
2030
2031 }
2032 }
2033 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002034 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002035 app.pid = startResult.pid;
2036 app.usingWrapper = startResult.usingWrapper;
2037 app.removed = false;
2038 synchronized (mPidsSelfLocked) {
2039 this.mPidsSelfLocked.put(startResult.pid, app);
2040 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2041 msg.obj = app;
2042 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2043 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045 } catch (RuntimeException e) {
2046 // XXX do better error recovery.
2047 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002048 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 }
2050 }
2051
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002052 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 if (resumed) {
2054 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2055 } else {
2056 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2057 }
2058 }
2059
Amith Yamasani742a6712011-05-04 14:49:28 -07002060 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002061 if (mHeadless) {
2062 // Added because none of the other calls to ensureBootCompleted seem to fire
2063 // when running headless.
2064 ensureBootCompleted();
2065 return false;
2066 }
2067
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002068 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2069 && mTopAction == null) {
2070 // We are running in factory test mode, but unable to find
2071 // the factory test app, so just sit around displaying the
2072 // error message and don't try to start anything.
2073 return false;
2074 }
2075 Intent intent = new Intent(
2076 mTopAction,
2077 mTopData != null ? Uri.parse(mTopData) : null);
2078 intent.setComponent(mTopComponent);
2079 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2080 intent.addCategory(Intent.CATEGORY_HOME);
2081 }
2082 ActivityInfo aInfo =
2083 intent.resolveActivityInfo(mContext.getPackageManager(),
2084 STOCK_PM_FLAGS);
2085 if (aInfo != null) {
2086 intent.setComponent(new ComponentName(
2087 aInfo.applicationInfo.packageName, aInfo.name));
2088 // Don't do this if the home app is currently being
2089 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002090 aInfo = new ActivityInfo(aInfo);
2091 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002092 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2093 aInfo.applicationInfo.uid);
2094 if (app == null || app.instrumentationClass == null) {
2095 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002096 mMainStack.startActivityLocked(null, intent, null, aInfo,
2097 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002098 }
2099 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002100
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002101 return true;
2102 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002103
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002104 /**
2105 * Starts the "new version setup screen" if appropriate.
2106 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002107 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002108 // Only do this once per boot.
2109 if (mCheckedForSetup) {
2110 return;
2111 }
2112
2113 // We will show this screen if the current one is a different
2114 // version than the last one shown, and we are not running in
2115 // low-level factory test mode.
2116 final ContentResolver resolver = mContext.getContentResolver();
2117 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2118 Settings.Secure.getInt(resolver,
2119 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2120 mCheckedForSetup = true;
2121
2122 // See if we should be showing the platform update setup UI.
2123 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2124 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2125 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2126
2127 // We don't allow third party apps to replace this.
2128 ResolveInfo ri = null;
2129 for (int i=0; ris != null && i<ris.size(); i++) {
2130 if ((ris.get(i).activityInfo.applicationInfo.flags
2131 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2132 ri = ris.get(i);
2133 break;
2134 }
2135 }
2136
2137 if (ri != null) {
2138 String vers = ri.activityInfo.metaData != null
2139 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2140 : null;
2141 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2142 vers = ri.activityInfo.applicationInfo.metaData.getString(
2143 Intent.METADATA_SETUP_VERSION);
2144 }
2145 String lastVers = Settings.Secure.getString(
2146 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2147 if (vers != null && !vers.equals(lastVers)) {
2148 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2149 intent.setComponent(new ComponentName(
2150 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002151 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2152 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002153 }
2154 }
2155 }
2156 }
2157
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002158 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002159 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002160 }
2161
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002162 void enforceNotIsolatedCaller(String caller) {
2163 if (UserId.isIsolated(Binder.getCallingUid())) {
2164 throw new SecurityException("Isolated process not allowed to call " + caller);
2165 }
2166 }
2167
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002168 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002169 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002170 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002171 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2172 }
2173 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002174
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002175 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002176 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2177 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002178 synchronized (this) {
2179 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2180 }
2181 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002182
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002183 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002184 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002185 synchronized (this) {
2186 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2187 }
2188 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002189
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002190 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002191 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2192 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002193 synchronized (this) {
2194 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002195 }
2196 }
2197
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002198 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002199 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002200 synchronized (this) {
2201 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2202 }
2203 }
2204
2205 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002206 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2207 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002208 synchronized (this) {
2209 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2210 }
2211 }
2212
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002213 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002214 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002215
2216 final int identHash = System.identityHashCode(r);
2217 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219
Jeff Sharkeya4620792011-05-20 15:29:23 -07002220 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2221 int i = mProcessObservers.beginBroadcast();
2222 while (i > 0) {
2223 i--;
2224 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2225 if (observer != null) {
2226 try {
2227 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2228 } catch (RemoteException e) {
2229 }
2230 }
2231 }
2232 mProcessObservers.finishBroadcast();
2233 }
2234
2235 private void dispatchProcessDied(int pid, int uid) {
2236 int i = mProcessObservers.beginBroadcast();
2237 while (i > 0) {
2238 i--;
2239 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2240 if (observer != null) {
2241 try {
2242 observer.onProcessDied(pid, uid);
2243 } catch (RemoteException e) {
2244 }
2245 }
2246 }
2247 mProcessObservers.finishBroadcast();
2248 }
2249
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002250 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002251 final int N = mPendingActivityLaunches.size();
2252 if (N <= 0) {
2253 return;
2254 }
2255 for (int i=0; i<N; i++) {
2256 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002258 pal.startFlags, doResume && i == (N-1));
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002259 }
2260 mPendingActivityLaunches.clear();
2261 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002262
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002263 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002264 Intent intent, String resolvedType, IBinder resultTo,
2265 String resultWho, int requestCode, int startFlags,
2266 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002267 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002268 int userId = 0;
2269 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2270 // Requesting home, set the identity to the current user
2271 // HACK!
2272 userId = mCurrentUserId;
2273 } else {
2274 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2275 // the current user's userId
2276 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2277 userId = 0;
2278 } else {
2279 userId = Binder.getOrigCallingUser();
2280 }
2281 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002282 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002283 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2284 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002285 }
2286
2287 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002288 Intent intent, String resolvedType, IBinder resultTo,
2289 String resultWho, int requestCode, int startFlags, String profileFile,
2290 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002291 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002292 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002293 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002294 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002295 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2296 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002297 return res;
2298 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002299
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002300 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002301 Intent intent, String resolvedType, IBinder resultTo,
2302 String resultWho, int requestCode, int startFlags, Configuration config,
2303 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002304 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002305 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags,
2307 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002308 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002309 }
2310
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002311 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002312 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002313 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002314 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002316 // Refuse possible leaked file descriptors
2317 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2318 throw new IllegalArgumentException("File descriptors passed in Intent");
2319 }
2320
2321 IIntentSender sender = intent.getTarget();
2322 if (!(sender instanceof PendingIntentRecord)) {
2323 throw new IllegalArgumentException("Bad PendingIntent object");
2324 }
2325
2326 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002327
2328 synchronized (this) {
2329 // If this is coming from the currently resumed activity, it is
2330 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002331 if (mMainStack.mResumedActivity != null
2332 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002333 Binder.getCallingUid()) {
2334 mAppSwitchesAllowedTime = 0;
2335 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002336 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002337 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2338 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002339 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002340 }
2341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002343 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 // Refuse possible leaked file descriptors
2345 if (intent != null && intent.hasFileDescriptors() == true) {
2346 throw new IllegalArgumentException("File descriptors passed in Intent");
2347 }
2348
2349 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002350 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2351 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 return false;
2353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 if (r.app == null || r.app.thread == null) {
2355 // The caller is not running... d'oh!
2356 return false;
2357 }
2358 intent = new Intent(intent);
2359 // The caller is not allowed to change the data.
2360 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2361 // And we are resetting to find the next component...
2362 intent.setComponent(null);
2363
2364 ActivityInfo aInfo = null;
2365 try {
2366 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002367 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002369 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370
2371 // Look for the original activity in the list...
2372 final int N = resolves != null ? resolves.size() : 0;
2373 for (int i=0; i<N; i++) {
2374 ResolveInfo rInfo = resolves.get(i);
2375 if (rInfo.activityInfo.packageName.equals(r.packageName)
2376 && rInfo.activityInfo.name.equals(r.info.name)) {
2377 // We found the current one... the next matching is
2378 // after it.
2379 i++;
2380 if (i<N) {
2381 aInfo = resolves.get(i).activityInfo;
2382 }
2383 break;
2384 }
2385 }
2386 } catch (RemoteException e) {
2387 }
2388
2389 if (aInfo == null) {
2390 // Nobody who is next!
2391 return false;
2392 }
2393
2394 intent.setComponent(new ComponentName(
2395 aInfo.applicationInfo.packageName, aInfo.name));
2396 intent.setFlags(intent.getFlags()&~(
2397 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2398 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2399 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2400 Intent.FLAG_ACTIVITY_NEW_TASK));
2401
2402 // Okay now we need to start the new activity, replacing the
2403 // currently running activity. This is a little tricky because
2404 // we want to start the new one as if the current one is finished,
2405 // but not finish the current one first so that there is no flicker.
2406 // And thus...
2407 final boolean wasFinishing = r.finishing;
2408 r.finishing = true;
2409
2410 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002411 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 final String resultWho = r.resultWho;
2413 final int requestCode = r.requestCode;
2414 r.resultTo = null;
2415 if (resultTo != null) {
2416 resultTo.removeResultsLocked(r, resultWho, requestCode);
2417 }
2418
2419 final long origId = Binder.clearCallingIdentity();
2420 // XXX we are not dealing with propagating grantedUriPermissions...
2421 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002423 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2424 resultWho, requestCode, -1, r.launchedFromUid, 0,
2425 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 Binder.restoreCallingIdentity(origId);
2427
2428 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002429 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 return false;
2431 }
2432 return true;
2433 }
2434 }
2435
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002436 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002438 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002439
2440 // This is so super not safe, that only the system (or okay root)
2441 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002442 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002443 final int callingUid = Binder.getCallingUid();
2444 if (callingUid != 0 && callingUid != Process.myUid()) {
2445 throw new SecurityException(
2446 "startActivityInPackage only available to the system");
2447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448
Amith Yamasani742a6712011-05-04 14:49:28 -07002449 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002450 resultTo, resultWho, requestCode, startFlags,
2451 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002452 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002453 }
2454
2455 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002457 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002458 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002459 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002460 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002461 }
2462
2463 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002464 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2465 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002466
2467 // This is so super not safe, that only the system (or okay root)
2468 // can do it.
2469 final int callingUid = Binder.getCallingUid();
2470 if (callingUid != 0 && callingUid != Process.myUid()) {
2471 throw new SecurityException(
2472 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002474 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002476 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 }
2478
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002479 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002481 // Quick case: check if the top-most recent task is the same.
2482 if (N > 0 && mRecentTasks.get(0) == task) {
2483 return;
2484 }
2485 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 for (int i=0; i<N; i++) {
2487 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002488 if (task.userId == tr.userId
2489 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2490 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 mRecentTasks.remove(i);
2492 i--;
2493 N--;
2494 if (task.intent == null) {
2495 // If the new recent task we are adding is not fully
2496 // specified, then replace it with the existing recent task.
2497 task = tr;
2498 }
2499 }
2500 }
2501 if (N >= MAX_RECENT_TASKS) {
2502 mRecentTasks.remove(N-1);
2503 }
2504 mRecentTasks.add(0, task);
2505 }
2506
2507 public void setRequestedOrientation(IBinder token,
2508 int requestedOrientation) {
2509 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002510 ActivityRecord r = mMainStack.isInStackLocked(token);
2511 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 return;
2513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002515 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002517 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002518 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 if (config != null) {
2520 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002521 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
2525 Binder.restoreCallingIdentity(origId);
2526 }
2527 }
2528
2529 public int getRequestedOrientation(IBinder token) {
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 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2534 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002535 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
2537 }
2538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 /**
2540 * This is the internal entry point for handling Activity.finish().
2541 *
2542 * @param token The Binder token referencing the Activity we want to finish.
2543 * @param resultCode Result code, if any, from this Activity.
2544 * @param resultData Result data (Intent), if any, from this Activity.
2545 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002546 * @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 -08002547 */
2548 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2549 // Refuse possible leaked file descriptors
2550 if (resultData != null && resultData.hasFileDescriptors() == true) {
2551 throw new IllegalArgumentException("File descriptors passed in Intent");
2552 }
2553
2554 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002555 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002557 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 if (next != null) {
2559 // ask watcher if this is allowed
2560 boolean resumeOK = true;
2561 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002562 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002564 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566
2567 if (!resumeOK) {
2568 return false;
2569 }
2570 }
2571 }
2572 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002573 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 resultData, "app-request");
2575 Binder.restoreCallingIdentity(origId);
2576 return res;
2577 }
2578 }
2579
Dianne Hackborn860755f2010-06-03 18:47:52 -07002580 public final void finishHeavyWeightApp() {
2581 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2582 != PackageManager.PERMISSION_GRANTED) {
2583 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2584 + Binder.getCallingPid()
2585 + ", uid=" + Binder.getCallingUid()
2586 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2587 Slog.w(TAG, msg);
2588 throw new SecurityException(msg);
2589 }
2590
2591 synchronized(this) {
2592 if (mHeavyWeightProcess == null) {
2593 return;
2594 }
2595
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002596 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002597 mHeavyWeightProcess.activities);
2598 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002599 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002600 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002601 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002602 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002604 null, "finish-heavy");
2605 }
2606 }
2607 }
2608
2609 mHeavyWeightProcess = null;
2610 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2611 }
2612 }
2613
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002614 public void crashApplication(int uid, int initialPid, String packageName,
2615 String message) {
2616 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2617 != PackageManager.PERMISSION_GRANTED) {
2618 String msg = "Permission Denial: crashApplication() from pid="
2619 + Binder.getCallingPid()
2620 + ", uid=" + Binder.getCallingUid()
2621 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2622 Slog.w(TAG, msg);
2623 throw new SecurityException(msg);
2624 }
2625
2626 synchronized(this) {
2627 ProcessRecord proc = null;
2628
2629 // Figure out which process to kill. We don't trust that initialPid
2630 // still has any relation to current pids, so must scan through the
2631 // list.
2632 synchronized (mPidsSelfLocked) {
2633 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2634 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002635 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002636 continue;
2637 }
2638 if (p.pid == initialPid) {
2639 proc = p;
2640 break;
2641 }
2642 for (String str : p.pkgList) {
2643 if (str.equals(packageName)) {
2644 proc = p;
2645 }
2646 }
2647 }
2648 }
2649
2650 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002651 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002652 + " initialPid=" + initialPid
2653 + " packageName=" + packageName);
2654 return;
2655 }
2656
2657 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002658 if (proc.pid == Process.myPid()) {
2659 Log.w(TAG, "crashApplication: trying to crash self!");
2660 return;
2661 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002662 long ident = Binder.clearCallingIdentity();
2663 try {
2664 proc.thread.scheduleCrash(message);
2665 } catch (RemoteException e) {
2666 }
2667 Binder.restoreCallingIdentity(ident);
2668 }
2669 }
2670 }
2671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 public final void finishSubActivity(IBinder token, String resultWho,
2673 int requestCode) {
2674 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002675 ActivityRecord self = mMainStack.isInStackLocked(token);
2676 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 return;
2678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679
2680 final long origId = Binder.clearCallingIdentity();
2681
2682 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002683 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2684 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 if (r.resultTo == self && r.requestCode == requestCode) {
2686 if ((r.resultWho == null && resultWho == null) ||
2687 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002688 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 Activity.RESULT_CANCELED, null, "request-sub");
2690 }
2691 }
2692 }
2693
2694 Binder.restoreCallingIdentity(origId);
2695 }
2696 }
2697
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002698 public boolean willActivityBeVisible(IBinder token) {
2699 synchronized(this) {
2700 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002701 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2702 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002703 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002704 return true;
2705 }
2706 if (r.fullscreen && !r.finishing) {
2707 return false;
2708 }
2709 }
2710 return true;
2711 }
2712 }
2713
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002714 public void overridePendingTransition(IBinder token, String packageName,
2715 int enterAnim, int exitAnim) {
2716 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002717 ActivityRecord self = mMainStack.isInStackLocked(token);
2718 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002719 return;
2720 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002721
2722 final long origId = Binder.clearCallingIdentity();
2723
2724 if (self.state == ActivityState.RESUMED
2725 || self.state == ActivityState.PAUSING) {
2726 mWindowManager.overridePendingAppTransition(packageName,
2727 enterAnim, exitAnim);
2728 }
2729
2730 Binder.restoreCallingIdentity(origId);
2731 }
2732 }
2733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 * Main function for removing an existing process from the activity manager
2736 * as a result of that process going away. Clears out all connections
2737 * to the process.
2738 */
2739 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002740 boolean restarting, boolean allowRestart) {
2741 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002743 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 }
2745
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002746 if (mProfileProc == app) {
2747 clearProfilerLocked();
2748 }
2749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002751 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2752 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2753 mMainStack.mPausingActivity = null;
2754 }
2755 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2756 mMainStack.mLastPausedActivity = null;
2757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758
2759 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761
2762 boolean atTop = true;
2763 boolean hasVisibleActivities = false;
2764
2765 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002767 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 TAG, "Removing app " + app + " from history with " + i + " entries");
2769 while (i > 0) {
2770 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002771 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002772 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2774 if (r.app == app) {
2775 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002776 if (ActivityStack.DEBUG_ADD_REMOVE) {
2777 RuntimeException here = new RuntimeException("here");
2778 here.fillInStackTrace();
2779 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2780 + ": haveState=" + r.haveState
2781 + " stateNotNeeded=" + r.stateNotNeeded
2782 + " finishing=" + r.finishing
2783 + " state=" + r.state, here);
2784 }
2785 if (!r.finishing) {
2786 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002787 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2788 System.identityHashCode(r),
2789 r.task.taskId, r.shortComponentName,
2790 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002791 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002792 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793
2794 } else {
2795 // We have the current state for this activity, so
2796 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002797 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 TAG, "Keeping entry, setting app to null");
2799 if (r.visible) {
2800 hasVisibleActivities = true;
2801 }
2802 r.app = null;
2803 r.nowVisible = false;
2804 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002805 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2806 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 r.icicle = null;
2808 }
2809 }
2810
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002811 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
2813 atTop = false;
2814 }
2815
2816 app.activities.clear();
2817
2818 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002819 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 + " running instrumentation " + app.instrumentationClass);
2821 Bundle info = new Bundle();
2822 info.putString("shortMsg", "Process crashed.");
2823 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2824 }
2825
2826 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002827 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 // If there was nothing to resume, and we are not already
2829 // restarting this process, but there is a visible activity that
2830 // is hosted by the process... then make sure all visible
2831 // activities are running, taking care of restarting this
2832 // process.
2833 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836 }
2837 }
2838 }
2839
2840 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2841 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002843 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2844 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2846 return i;
2847 }
2848 }
2849 return -1;
2850 }
2851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 IApplicationThread thread) {
2854 if (thread == null) {
2855 return null;
2856 }
2857
2858 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002859 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002862 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 IApplicationThread thread) {
2864
2865 mProcDeaths[0]++;
2866
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002867 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2868 synchronized (stats) {
2869 stats.noteProcessDiedLocked(app.info.uid, pid);
2870 }
2871
Magnus Edlund7bb25812010-02-24 15:45:06 +01002872 // Clean up already done if the process has been re-started.
2873 if (app.pid == pid && app.thread != null &&
2874 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002875 if (!app.killedBackground) {
2876 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2877 + ") has died.");
2878 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002879 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002880 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 TAG, "Dying app: " + app + ", pid: " + pid
2882 + ", thread: " + thread.asBinder());
2883 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002884 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885
2886 if (doLowMem) {
2887 // If there are no longer any background processes running,
2888 // and the app that died was not running instrumentation,
2889 // then tell everyone we are now low on memory.
2890 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002891 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2892 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002893 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 haveBg = true;
2895 break;
2896 }
2897 }
2898
2899 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002900 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002901 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002902 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2903 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002904 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002905 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2906 // The low memory report is overriding any current
2907 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002908 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002909 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002910 rec.lastRequestedGc = 0;
2911 } else {
2912 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002914 rec.reportLowMemory = true;
2915 rec.lastLowMemory = now;
2916 mProcessesToGc.remove(rec);
2917 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 }
2919 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002920 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002921 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 }
2923 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002924 } else if (app.pid != pid) {
2925 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002926 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002927 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002928 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002929 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002930 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 + thread.asBinder());
2932 }
2933 }
2934
Dan Egnor42471dd2010-01-07 17:25:22 -08002935 /**
2936 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002937 * @param clearTraces causes the dump file to be erased prior to the new
2938 * traces being written, if true; when false, the new traces will be
2939 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002940 * @param firstPids of dalvik VM processes to dump stack traces for first
2941 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002942 * @return file containing stack traces, or null if no dump file is configured
2943 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002944 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2945 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002946 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2947 if (tracesPath == null || tracesPath.length() == 0) {
2948 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002950
2951 File tracesFile = new File(tracesPath);
2952 try {
2953 File tracesDir = tracesFile.getParentFile();
2954 if (!tracesDir.exists()) tracesFile.mkdirs();
2955 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2956
Christopher Tate6ee412d2010-05-28 12:01:56 -07002957 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002958 tracesFile.createNewFile();
2959 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2960 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002961 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002962 return null;
2963 }
2964
2965 // Use a FileObserver to detect when traces finish writing.
2966 // The order of traces is considered important to maintain for legibility.
2967 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2968 public synchronized void onEvent(int event, String path) { notify(); }
2969 };
2970
2971 try {
2972 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002973
2974 // First collect all of the stacks of the most important pids.
2975 try {
2976 int num = firstPids.size();
2977 for (int i = 0; i < num; i++) {
2978 synchronized (observer) {
2979 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2980 observer.wait(200); // Wait for write-close, give up after 200msec
2981 }
2982 }
2983 } catch (InterruptedException e) {
2984 Log.wtf(TAG, e);
2985 }
2986
2987 // Next measure CPU usage.
2988 if (processStats != null) {
2989 processStats.init();
2990 System.gc();
2991 processStats.update();
2992 try {
2993 synchronized (processStats) {
2994 processStats.wait(500); // measure over 1/2 second.
2995 }
2996 } catch (InterruptedException e) {
2997 }
2998 processStats.update();
2999
3000 // We'll take the stack crawls of just the top apps using CPU.
3001 final int N = processStats.countWorkingStats();
3002 int numProcs = 0;
3003 for (int i=0; i<N && numProcs<5; i++) {
3004 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3005 if (lastPids.indexOfKey(stats.pid) >= 0) {
3006 numProcs++;
3007 try {
3008 synchronized (observer) {
3009 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3010 observer.wait(200); // Wait for write-close, give up after 200msec
3011 }
3012 } catch (InterruptedException e) {
3013 Log.wtf(TAG, e);
3014 }
3015
3016 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003017 }
3018 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003019
3020 return tracesFile;
3021
Dan Egnor42471dd2010-01-07 17:25:22 -08003022 } finally {
3023 observer.stopWatching();
3024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 }
3026
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003027 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3028 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003029 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3030 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3031
Dianne Hackborn287952c2010-09-22 22:34:31 -07003032 if (mController != null) {
3033 try {
3034 // 0 == continue, -1 = kill process immediately
3035 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3036 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3037 } catch (RemoteException e) {
3038 mController = null;
3039 }
3040 }
3041
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003042 long anrTime = SystemClock.uptimeMillis();
3043 if (MONITOR_CPU_USAGE) {
3044 updateCpuStatsNow();
3045 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003046
3047 synchronized (this) {
3048 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3049 if (mShuttingDown) {
3050 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3051 return;
3052 } else if (app.notResponding) {
3053 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3054 return;
3055 } else if (app.crashing) {
3056 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3057 return;
3058 }
3059
3060 // In case we come through here for the same app before completing
3061 // this one, mark as anring now so we will bail out.
3062 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003063
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003064 // Log the ANR to the event log.
3065 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3066 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003067
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003068 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003069 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003070
3071 int parentPid = app.pid;
3072 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003073 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003074
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003075 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003076
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003077 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3078 ProcessRecord r = mLruProcesses.get(i);
3079 if (r != null && r.thread != null) {
3080 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003081 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3082 if (r.persistent) {
3083 firstPids.add(pid);
3084 } else {
3085 lastPids.put(pid, Boolean.TRUE);
3086 }
3087 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 }
3090 }
3091
Dan Egnor42471dd2010-01-07 17:25:22 -08003092 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003093 StringBuilder info = mStringBuilder;
3094 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003095 info.append("ANR in ").append(app.processName);
3096 if (activity != null && activity.shortComponentName != null) {
3097 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003098 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003099 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003101 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003103 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003104 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106
Dianne Hackborn287952c2010-09-22 22:34:31 -07003107 final ProcessStats processStats = new ProcessStats(true);
3108
3109 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3110
Dan Egnor42471dd2010-01-07 17:25:22 -08003111 String cpuInfo = null;
3112 if (MONITOR_CPU_USAGE) {
3113 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003114 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003115 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003116 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003117 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003118 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 }
3120
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003121 info.append(processStats.printCurrentState(anrTime));
3122
Joe Onorato8a9b2202010-02-26 18:56:32 -08003123 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003124 if (tracesFile == null) {
3125 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3126 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3127 }
3128
Jeff Sharkeya353d262011-10-28 11:12:06 -07003129 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3130 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003131
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003132 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003134 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3135 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003137 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3138 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 }
3140 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003141 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143 }
3144
Dan Egnor42471dd2010-01-07 17:25:22 -08003145 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3146 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3147 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003148
3149 synchronized (this) {
3150 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003151 Slog.w(TAG, "Killing " + app + ": background ANR");
3152 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3153 app.processName, app.setAdj, "background ANR");
3154 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003155 return;
3156 }
3157
3158 // Set the app's notResponding state, and look up the errorReportReceiver
3159 makeAppNotRespondingLocked(app,
3160 activity != null ? activity.shortComponentName : null,
3161 annotation != null ? "ANR " + annotation : "ANR",
3162 info.toString());
3163
3164 // Bring up the infamous App Not Responding dialog
3165 Message msg = Message.obtain();
3166 HashMap map = new HashMap();
3167 msg.what = SHOW_NOT_RESPONDING_MSG;
3168 msg.obj = map;
3169 map.put("app", app);
3170 if (activity != null) {
3171 map.put("activity", activity);
3172 }
3173
3174 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 }
3177
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003178 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3179 if (!mLaunchWarningShown) {
3180 mLaunchWarningShown = true;
3181 mHandler.post(new Runnable() {
3182 @Override
3183 public void run() {
3184 synchronized (ActivityManagerService.this) {
3185 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3186 d.show();
3187 mHandler.postDelayed(new Runnable() {
3188 @Override
3189 public void run() {
3190 synchronized (ActivityManagerService.this) {
3191 d.dismiss();
3192 mLaunchWarningShown = false;
3193 }
3194 }
3195 }, 4000);
3196 }
3197 }
3198 });
3199 }
3200 }
3201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003203 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003204 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 int uid = Binder.getCallingUid();
3206 int pid = Binder.getCallingPid();
3207 long callingId = Binder.clearCallingIdentity();
3208 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003209 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 int pkgUid = -1;
3211 synchronized(this) {
3212 try {
3213 pkgUid = pm.getPackageUid(packageName);
3214 } catch (RemoteException e) {
3215 }
3216 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003217 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 return false;
3219 }
3220 if (uid == pkgUid || checkComponentPermission(
3221 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003222 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003224 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 } else {
3226 throw new SecurityException(pid+" does not have permission:"+
3227 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3228 "for process:"+packageName);
3229 }
3230 }
3231
3232 try {
3233 //clear application user data
3234 pm.clearApplicationUserData(packageName, observer);
3235 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3236 Uri.fromParts("package", packageName, null));
3237 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003238 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003239 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 } catch (RemoteException e) {
3241 }
3242 } finally {
3243 Binder.restoreCallingIdentity(callingId);
3244 }
3245 return true;
3246 }
3247
Dianne Hackborn03abb812010-01-04 18:43:19 -08003248 public void killBackgroundProcesses(final String packageName) {
3249 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3250 != PackageManager.PERMISSION_GRANTED &&
3251 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3252 != PackageManager.PERMISSION_GRANTED) {
3253 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 + Binder.getCallingPid()
3255 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003256 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003257 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 throw new SecurityException(msg);
3259 }
3260
3261 long callingId = Binder.clearCallingIdentity();
3262 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003263 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 int pkgUid = -1;
3265 synchronized(this) {
3266 try {
3267 pkgUid = pm.getPackageUid(packageName);
3268 } catch (RemoteException e) {
3269 }
3270 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003271 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 return;
3273 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003274 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003275 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3276 }
3277 } finally {
3278 Binder.restoreCallingIdentity(callingId);
3279 }
3280 }
3281
3282 public void killAllBackgroundProcesses() {
3283 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3284 != PackageManager.PERMISSION_GRANTED) {
3285 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3286 + Binder.getCallingPid()
3287 + ", uid=" + Binder.getCallingUid()
3288 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3289 Slog.w(TAG, msg);
3290 throw new SecurityException(msg);
3291 }
3292
3293 long callingId = Binder.clearCallingIdentity();
3294 try {
3295 synchronized(this) {
3296 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3297 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3298 final int NA = apps.size();
3299 for (int ia=0; ia<NA; ia++) {
3300 ProcessRecord app = apps.valueAt(ia);
3301 if (app.persistent) {
3302 // we don't kill persistent processes
3303 continue;
3304 }
3305 if (app.removed) {
3306 procs.add(app);
3307 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3308 app.removed = true;
3309 procs.add(app);
3310 }
3311 }
3312 }
3313
3314 int N = procs.size();
3315 for (int i=0; i<N; i++) {
3316 removeProcessLocked(procs.get(i), false, true, "kill all background");
3317 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003318 }
3319 } finally {
3320 Binder.restoreCallingIdentity(callingId);
3321 }
3322 }
3323
3324 public void forceStopPackage(final String packageName) {
3325 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3326 != PackageManager.PERMISSION_GRANTED) {
3327 String msg = "Permission Denial: forceStopPackage() from pid="
3328 + Binder.getCallingPid()
3329 + ", uid=" + Binder.getCallingUid()
3330 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003331 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003332 throw new SecurityException(msg);
3333 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003334 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003335 long callingId = Binder.clearCallingIdentity();
3336 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003337 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003338 int pkgUid = -1;
3339 synchronized(this) {
3340 try {
3341 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003342 // Convert the uid to the one for the calling user
3343 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003344 } catch (RemoteException e) {
3345 }
3346 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003347 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003348 return;
3349 }
3350 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003351 try {
3352 pm.setPackageStoppedState(packageName, true);
3353 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003354 } catch (IllegalArgumentException e) {
3355 Slog.w(TAG, "Failed trying to unstop package "
3356 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 }
3359 } finally {
3360 Binder.restoreCallingIdentity(callingId);
3361 }
3362 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003363
3364 /*
3365 * The pkg name and uid have to be specified.
3366 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3367 */
3368 public void killApplicationWithUid(String pkg, int uid) {
3369 if (pkg == null) {
3370 return;
3371 }
3372 // Make sure the uid is valid.
3373 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003374 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003375 return;
3376 }
3377 int callerUid = Binder.getCallingUid();
3378 // Only the system server can kill an application
3379 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003380 // Post an aysnc message to kill the application
3381 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3382 msg.arg1 = uid;
3383 msg.arg2 = 0;
3384 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003385 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003386 } else {
3387 throw new SecurityException(callerUid + " cannot kill pkg: " +
3388 pkg);
3389 }
3390 }
3391
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003392 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003393 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003394 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003395 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003396 if (reason != null) {
3397 intent.putExtra("reason", reason);
3398 }
3399
3400 final int uid = Binder.getCallingUid();
3401 final long origId = Binder.clearCallingIdentity();
3402 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003403 mWindowManager.closeSystemDialogs(reason);
3404
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003405 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003406 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003407 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003408 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003409 Activity.RESULT_CANCELED, null, "close-sys");
3410 }
3411 }
3412
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003413 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003414 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003415 }
3416 Binder.restoreCallingIdentity(origId);
3417 }
3418
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003419 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003420 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003421 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003422 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3423 for (int i=pids.length-1; i>=0; i--) {
3424 infos[i] = new Debug.MemoryInfo();
3425 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003426 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003427 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003428 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003429
Dianne Hackbornb437e092011-08-05 17:50:29 -07003430 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003431 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003432 long[] pss = new long[pids.length];
3433 for (int i=pids.length-1; i>=0; i--) {
3434 pss[i] = Debug.getPss(pids[i]);
3435 }
3436 return pss;
3437 }
3438
Christopher Tate5e1ab332009-09-01 20:32:49 -07003439 public void killApplicationProcess(String processName, int uid) {
3440 if (processName == null) {
3441 return;
3442 }
3443
3444 int callerUid = Binder.getCallingUid();
3445 // Only the system server can kill an application
3446 if (callerUid == Process.SYSTEM_UID) {
3447 synchronized (this) {
3448 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003449 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003450 try {
3451 app.thread.scheduleSuicide();
3452 } catch (RemoteException e) {
3453 // If the other end already died, then our work here is done.
3454 }
3455 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003456 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003457 + processName + " / " + uid);
3458 }
3459 }
3460 } else {
3461 throw new SecurityException(callerUid + " cannot kill app process: " +
3462 processName);
3463 }
3464 }
3465
Dianne Hackborn03abb812010-01-04 18:43:19 -08003466 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003467 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3469 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003470 if (!mProcessesReady) {
3471 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 intent.putExtra(Intent.EXTRA_UID, uid);
3474 broadcastIntentLocked(null, null, intent,
3475 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003476 false, false,
3477 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 }
3479
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003480 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003481 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003482 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003483 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484
Dianne Hackborn03abb812010-01-04 18:43:19 -08003485 // Remove all processes this package may have touched: all with the
3486 // same UID (except for the system or root user), and all whose name
3487 // matches the package name.
3488 final String procNamePrefix = packageName + ":";
3489 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3490 final int NA = apps.size();
3491 for (int ia=0; ia<NA; ia++) {
3492 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003493 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003494 // we don't kill persistent processes
3495 continue;
3496 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003497 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003498 if (doit) {
3499 procs.add(app);
3500 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003501 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3502 || app.processName.equals(packageName)
3503 || app.processName.startsWith(procNamePrefix)) {
3504 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003505 if (!doit) {
3506 return true;
3507 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003508 app.removed = true;
3509 procs.add(app);
3510 }
3511 }
3512 }
3513 }
3514
3515 int N = procs.size();
3516 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003517 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003518 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003519 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003520 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003521
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003522 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003523 boolean callerWillRestart, boolean purgeCache, boolean doit,
3524 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003525 int i;
3526 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 if (uid < 0) {
3529 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003530 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 } catch (RemoteException e) {
3532 }
3533 }
3534
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003535 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003536 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003537
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003538 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3539 while (badApps.hasNext()) {
3540 SparseArray<Long> ba = badApps.next();
3541 if (ba.get(uid) != null) {
3542 badApps.remove();
3543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
3545 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003546
3547 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003548 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003550 TaskRecord lastTask = null;
3551 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003552 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003553 final boolean samePackage = r.packageName.equals(name);
3554 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003555 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003556 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003557 if (r.finishing) {
3558 // If this activity is just finishing, then it is not
3559 // interesting as far as something to stop.
3560 continue;
3561 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003562 return true;
3563 }
3564 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003565 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003566 if (samePackage) {
3567 if (r.app != null) {
3568 r.app.removed = true;
3569 }
3570 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003572 lastTask = r.task;
3573 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3574 null, "force-stop")) {
3575 i--;
3576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
3578 }
3579
3580 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003581 int userId = UserId.getUserId(uid);
3582 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003583 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003584 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003585 if (!doit) {
3586 return true;
3587 }
3588 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003589 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 if (service.app != null) {
3591 service.app.removed = true;
3592 }
3593 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003594 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 services.add(service);
3596 }
3597 }
3598
3599 N = services.size();
3600 for (i=0; i<N; i++) {
3601 bringDownServiceLocked(services.get(i), true);
3602 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003603
3604 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003605 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003606 if (provider.info.packageName.equals(name)
3607 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3608 if (!doit) {
3609 return true;
3610 }
3611 didSomething = true;
3612 providers.add(provider);
3613 }
3614 }
3615
3616 N = providers.size();
3617 for (i=0; i<N; i++) {
3618 removeDyingProviderLocked(null, providers.get(i));
3619 }
3620
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003621 if (doit) {
3622 if (purgeCache) {
3623 AttributeCache ac = AttributeCache.instance();
3624 if (ac != null) {
3625 ac.removePackage(name);
3626 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003627 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003628 if (mBooted) {
3629 mMainStack.resumeTopActivityLocked(null);
3630 mMainStack.scheduleIdleLocked();
3631 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003632 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003633
3634 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 }
3636
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003637 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003638 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003640 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003641 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003642 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 + "/" + uid + ")");
3644
3645 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003646 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003647 if (mHeavyWeightProcess == app) {
3648 mHeavyWeightProcess = null;
3649 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 boolean needRestart = false;
3652 if (app.pid > 0 && app.pid != MY_PID) {
3653 int pid = app.pid;
3654 synchronized (mPidsSelfLocked) {
3655 mPidsSelfLocked.remove(pid);
3656 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3657 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003658 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003659 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003660 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003661 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003663 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003665 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 } else {
3667 needRestart = true;
3668 }
3669 }
3670 } else {
3671 mRemovedProcesses.add(app);
3672 }
3673
3674 return needRestart;
3675 }
3676
3677 private final void processStartTimedOutLocked(ProcessRecord app) {
3678 final int pid = app.pid;
3679 boolean gone = false;
3680 synchronized (mPidsSelfLocked) {
3681 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3682 if (knownApp != null && knownApp.thread == null) {
3683 mPidsSelfLocked.remove(pid);
3684 gone = true;
3685 }
3686 }
3687
3688 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003689 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003690 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003691 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003692 mProcessNames.remove(app.processName, app.uid);
3693 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003694 if (mHeavyWeightProcess == app) {
3695 mHeavyWeightProcess = null;
3696 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3697 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003698 // Take care of any launching providers waiting for this process.
3699 checkAppInLaunchingProvidersLocked(app, true);
3700 // Take care of any services that are waiting for the process.
3701 for (int i=0; i<mPendingServices.size(); i++) {
3702 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003703 if ((app.uid == sr.appInfo.uid
3704 && app.processName.equals(sr.processName))
3705 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003706 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003707 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003708 mPendingServices.remove(i);
3709 i--;
3710 bringDownServiceLocked(sr, true);
3711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003713 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3714 app.processName, app.setAdj, "start timeout");
3715 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003716 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003717 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003718 try {
3719 IBackupManager bm = IBackupManager.Stub.asInterface(
3720 ServiceManager.getService(Context.BACKUP_SERVICE));
3721 bm.agentDisconnected(app.info.packageName);
3722 } catch (RemoteException e) {
3723 // Can't happen; the backup manager is local
3724 }
3725 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003726 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003727 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003728 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003731 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 }
3733 }
3734
3735 private final boolean attachApplicationLocked(IApplicationThread thread,
3736 int pid) {
3737
3738 // Find the application record that is being attached... either via
3739 // the pid if we are running in multiple processes, or just pull the
3740 // next app record if we are emulating process with anonymous threads.
3741 ProcessRecord app;
3742 if (pid != MY_PID && pid >= 0) {
3743 synchronized (mPidsSelfLocked) {
3744 app = mPidsSelfLocked.get(pid);
3745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 } else {
3747 app = null;
3748 }
3749
3750 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003751 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003753 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003755 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 } else {
3757 try {
3758 thread.scheduleExit();
3759 } catch (Exception e) {
3760 // Ignore exceptions.
3761 }
3762 }
3763 return false;
3764 }
3765
3766 // If this application record is still attached to a previous
3767 // process, clean it up now.
3768 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003769 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 }
3771
3772 // Tell the process all about itself.
3773
Joe Onorato8a9b2202010-02-26 18:56:32 -08003774 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 TAG, "Binding process pid " + pid + " to record " + app);
3776
3777 String processName = app.processName;
3778 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003779 AppDeathRecipient adr = new AppDeathRecipient(
3780 app, pid, thread);
3781 thread.asBinder().linkToDeath(adr, 0);
3782 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 } catch (RemoteException e) {
3784 app.resetPackageList();
3785 startProcessLocked(app, "link fail", processName);
3786 return false;
3787 }
3788
Doug Zongker2bec3d42009-12-04 12:52:44 -08003789 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790
3791 app.thread = thread;
3792 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003793 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3794 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 app.forcingToForeground = null;
3796 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003797 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 app.debugging = false;
3799
3800 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3801
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003802 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003803 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003805 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003806 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003807 }
3808
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 TAG, "New app record " + app
3811 + " thread=" + thread.asBinder() + " pid=" + pid);
3812 try {
3813 int testMode = IApplicationThread.DEBUG_OFF;
3814 if (mDebugApp != null && mDebugApp.equals(processName)) {
3815 testMode = mWaitForDebugger
3816 ? IApplicationThread.DEBUG_WAIT
3817 : IApplicationThread.DEBUG_ON;
3818 app.debugging = true;
3819 if (mDebugTransient) {
3820 mDebugApp = mOrigDebugApp;
3821 mWaitForDebugger = mOrigWaitForDebugger;
3822 }
3823 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003824 String profileFile = app.instrumentationProfileFile;
3825 ParcelFileDescriptor profileFd = null;
3826 boolean profileAutoStop = false;
3827 if (mProfileApp != null && mProfileApp.equals(processName)) {
3828 mProfileProc = app;
3829 profileFile = mProfileFile;
3830 profileFd = mProfileFd;
3831 profileAutoStop = mAutoStopProfiler;
3832 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003833 boolean enableOpenGlTrace = false;
3834 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3835 enableOpenGlTrace = true;
3836 mOpenGlTraceApp = null;
3837 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003838
Christopher Tate181fafa2009-05-14 11:12:14 -07003839 // If the app is being launched for restore or full backup, set it up specially
3840 boolean isRestrictedBackupMode = false;
3841 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3842 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003843 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003844 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3845 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003846
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003847 ensurePackageDexOpt(app.instrumentationInfo != null
3848 ? app.instrumentationInfo.packageName
3849 : app.info.packageName);
3850 if (app.instrumentationClass != null) {
3851 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003852 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003853 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003854 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003855 ApplicationInfo appInfo = app.instrumentationInfo != null
3856 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003857 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003858 if (profileFd != null) {
3859 profileFd = profileFd.dup();
3860 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003861 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003862 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003863 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3864 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003865 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003866 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003867 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003868 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 } catch (Exception e) {
3870 // todo: Yikes! What should we do? For now we will try to
3871 // start another process, but that could easily get us in
3872 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003873 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874
3875 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003876 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 startProcessLocked(app, "bind fail", processName);
3878 return false;
3879 }
3880
3881 // Remove this record from the list of starting applications.
3882 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003883 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3884 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 mProcessesOnHold.remove(app);
3886
3887 boolean badApp = false;
3888 boolean didSomething = false;
3889
3890 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003891 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003892 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003893 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 && processName.equals(hr.processName)) {
3895 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003896 if (mHeadless) {
3897 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3898 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 didSomething = true;
3900 }
3901 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003902 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 + hr.intent.getComponent().flattenToShortString(), e);
3904 badApp = true;
3905 }
3906 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003907 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
3910
3911 // Find any services that should be running in this process...
3912 if (!badApp && mPendingServices.size() > 0) {
3913 ServiceRecord sr = null;
3914 try {
3915 for (int i=0; i<mPendingServices.size(); i++) {
3916 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003917 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3918 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 continue;
3920 }
3921
3922 mPendingServices.remove(i);
3923 i--;
3924 realStartServiceLocked(sr, app);
3925 didSomething = true;
3926 }
3927 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003928 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 + sr.shortName, e);
3930 badApp = true;
3931 }
3932 }
3933
Christopher Tatef46723b2012-01-26 14:19:24 -08003934 // Check if a next-broadcast receiver is in this process...
3935 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003937 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003939 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 }
3942 }
3943
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003945 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003946 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003947 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003948 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003949 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3950 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3951 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003952 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003953 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003954 e.printStackTrace();
3955 }
3956 }
3957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 if (badApp) {
3959 // todo: Also need to kill application to deal with all
3960 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003961 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 return false;
3963 }
3964
3965 if (!didSomething) {
3966 updateOomAdjLocked();
3967 }
3968
3969 return true;
3970 }
3971
3972 public final void attachApplication(IApplicationThread thread) {
3973 synchronized (this) {
3974 int callingPid = Binder.getCallingPid();
3975 final long origId = Binder.clearCallingIdentity();
3976 attachApplicationLocked(thread, callingPid);
3977 Binder.restoreCallingIdentity(origId);
3978 }
3979 }
3980
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003981 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003983 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3984 if (stopProfiling) {
3985 synchronized (this) {
3986 if (mProfileProc == r.app) {
3987 if (mProfileFd != null) {
3988 try {
3989 mProfileFd.close();
3990 } catch (IOException e) {
3991 }
3992 clearProfilerLocked();
3993 }
3994 }
3995 }
3996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 Binder.restoreCallingIdentity(origId);
3998 }
3999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004001 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004002 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 mWindowManager.enableScreenAfterBoot();
4004 }
4005
Dianne Hackborn661cd522011-08-22 00:26:20 -07004006 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004007 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004008 mWindowManager.showBootMessage(msg, always);
4009 }
4010
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004011 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004012 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004013 synchronized (this) {
4014 mMainStack.dismissKeyguardOnNextActivityLocked();
4015 }
4016 }
4017
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004018 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004019 IntentFilter pkgFilter = new IntentFilter();
4020 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4021 pkgFilter.addDataScheme("package");
4022 mContext.registerReceiver(new BroadcastReceiver() {
4023 @Override
4024 public void onReceive(Context context, Intent intent) {
4025 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4026 if (pkgs != null) {
4027 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004028 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004029 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004030 setResultCode(Activity.RESULT_OK);
4031 return;
4032 }
4033 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004034 }
4035 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004036 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004037 }, pkgFilter);
4038
4039 synchronized (this) {
4040 // Ensure that any processes we had put on hold are now started
4041 // up.
4042 final int NP = mProcessesOnHold.size();
4043 if (NP > 0) {
4044 ArrayList<ProcessRecord> procs =
4045 new ArrayList<ProcessRecord>(mProcessesOnHold);
4046 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004047 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4048 + procs.get(ip));
4049 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004050 }
4051 }
4052
4053 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004054 // Start looking for apps that are abusing wake locks.
4055 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004056 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004057 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004058 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004059 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004060 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004061 broadcastIntentLocked(null, null,
4062 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4063 null, null, 0, null, null,
4064 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004065 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004066 }
4067 }
4068 }
4069
4070 final void ensureBootCompleted() {
4071 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004072 boolean enableScreen;
4073 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004074 booting = mBooting;
4075 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004076 enableScreen = !mBooted;
4077 mBooted = true;
4078 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004079
4080 if (booting) {
4081 finishBooting();
4082 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004083
4084 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004085 enableScreenAfterBoot();
4086 }
4087 }
4088
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004089 public final void activityPaused(IBinder token) {
4090 final long origId = Binder.clearCallingIdentity();
4091 mMainStack.activityPaused(token, false);
4092 Binder.restoreCallingIdentity(origId);
4093 }
4094
4095 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4096 CharSequence description) {
4097 if (localLOGV) Slog.v(
4098 TAG, "Activity stopped: token=" + token);
4099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 // Refuse possible leaked file descriptors
4101 if (icicle != null && icicle.hasFileDescriptors()) {
4102 throw new IllegalArgumentException("File descriptors passed in Bundle");
4103 }
4104
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004105 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106
4107 final long origId = Binder.clearCallingIdentity();
4108
4109 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004110 r = mMainStack.isInStackLocked(token);
4111 if (r != null) {
4112 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 }
4114 }
4115
4116 if (r != null) {
4117 sendPendingThumbnail(r, null, null, null, false);
4118 }
4119
4120 trimApplications();
4121
4122 Binder.restoreCallingIdentity(origId);
4123 }
4124
4125 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004126 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
4129
4130 public String getCallingPackage(IBinder token) {
4131 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004132 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004133 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
4135 }
4136
4137 public ComponentName getCallingActivity(IBinder token) {
4138 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004139 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 return r != null ? r.intent.getComponent() : null;
4141 }
4142 }
4143
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004144 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004145 ActivityRecord r = mMainStack.isInStackLocked(token);
4146 if (r == null) {
4147 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004149 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 }
4151
4152 public ComponentName getActivityClassForToken(IBinder token) {
4153 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004154 ActivityRecord r = mMainStack.isInStackLocked(token);
4155 if (r == null) {
4156 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004158 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
4160 }
4161
4162 public String getPackageForToken(IBinder token) {
4163 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004164 ActivityRecord r = mMainStack.isInStackLocked(token);
4165 if (r == null) {
4166 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004168 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170 }
4171
4172 public IIntentSender getIntentSender(int type,
4173 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004174 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004175 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004177 if (intents != null) {
4178 if (intents.length < 1) {
4179 throw new IllegalArgumentException("Intents array length must be >= 1");
4180 }
4181 for (int i=0; i<intents.length; i++) {
4182 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004183 if (intent != null) {
4184 if (intent.hasFileDescriptors()) {
4185 throw new IllegalArgumentException("File descriptors passed in Intent");
4186 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004187 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004188 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4189 throw new IllegalArgumentException(
4190 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4191 }
4192 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004193 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004194 }
4195 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004196 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004197 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004198 }
4199 }
4200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 synchronized(this) {
4202 int callingUid = Binder.getCallingUid();
4203 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004204 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004205 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004207 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 String msg = "Permission Denial: getIntentSender() from pid="
4209 + Binder.getCallingPid()
4210 + ", uid=" + Binder.getCallingUid()
4211 + ", (need uid=" + uid + ")"
4212 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004213 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 throw new SecurityException(msg);
4215 }
4216 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004217
Amith Yamasani742a6712011-05-04 14:49:28 -07004218 if (DEBUG_MU)
4219 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4220 + Binder.getOrigCallingUid());
4221 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004222 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 } catch (RemoteException e) {
4225 throw new SecurityException(e);
4226 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004227 }
4228 }
4229
4230 IIntentSender getIntentSenderLocked(int type,
4231 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004232 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004233 if (DEBUG_MU)
4234 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004235 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004236 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004237 activity = mMainStack.isInStackLocked(token);
4238 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004239 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004241 if (activity.finishing) {
4242 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004244 }
4245
4246 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4247 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4248 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4249 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4250 |PendingIntent.FLAG_UPDATE_CURRENT);
4251
4252 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4253 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004254 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004255 WeakReference<PendingIntentRecord> ref;
4256 ref = mIntentSenderRecords.get(key);
4257 PendingIntentRecord rec = ref != null ? ref.get() : null;
4258 if (rec != null) {
4259 if (!cancelCurrent) {
4260 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004261 if (rec.key.requestIntent != null) {
4262 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4263 }
4264 if (intents != null) {
4265 intents[intents.length-1] = rec.key.requestIntent;
4266 rec.key.allIntents = intents;
4267 rec.key.allResolvedTypes = resolvedTypes;
4268 } else {
4269 rec.key.allIntents = null;
4270 rec.key.allResolvedTypes = null;
4271 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 return rec;
4274 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004275 rec.canceled = true;
4276 mIntentSenderRecords.remove(key);
4277 }
4278 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 return rec;
4280 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004281 rec = new PendingIntentRecord(this, key, callingUid);
4282 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004283 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004284 if (activity.pendingResults == null) {
4285 activity.pendingResults
4286 = new HashSet<WeakReference<PendingIntentRecord>>();
4287 }
4288 activity.pendingResults.add(rec.ref);
4289 }
4290 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292
4293 public void cancelIntentSender(IIntentSender sender) {
4294 if (!(sender instanceof PendingIntentRecord)) {
4295 return;
4296 }
4297 synchronized(this) {
4298 PendingIntentRecord rec = (PendingIntentRecord)sender;
4299 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004300 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 .getPackageUid(rec.key.packageName);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004302 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 String msg = "Permission Denial: cancelIntentSender() from pid="
4304 + Binder.getCallingPid()
4305 + ", uid=" + Binder.getCallingUid()
4306 + " is not allowed to cancel packges "
4307 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004308 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 throw new SecurityException(msg);
4310 }
4311 } catch (RemoteException e) {
4312 throw new SecurityException(e);
4313 }
4314 cancelIntentSenderLocked(rec, true);
4315 }
4316 }
4317
4318 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4319 rec.canceled = true;
4320 mIntentSenderRecords.remove(rec.key);
4321 if (cleanActivity && rec.key.activity != null) {
4322 rec.key.activity.pendingResults.remove(rec.ref);
4323 }
4324 }
4325
4326 public String getPackageForIntentSender(IIntentSender pendingResult) {
4327 if (!(pendingResult instanceof PendingIntentRecord)) {
4328 return null;
4329 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004330 try {
4331 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4332 return res.key.packageName;
4333 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 }
4335 return null;
4336 }
4337
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004338 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4339 if (!(pendingResult instanceof PendingIntentRecord)) {
4340 return false;
4341 }
4342 try {
4343 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4344 if (res.key.allIntents == null) {
4345 return false;
4346 }
4347 for (int i=0; i<res.key.allIntents.length; i++) {
4348 Intent intent = res.key.allIntents[i];
4349 if (intent.getPackage() != null && intent.getComponent() != null) {
4350 return false;
4351 }
4352 }
4353 return true;
4354 } catch (ClassCastException e) {
4355 }
4356 return false;
4357 }
4358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 public void setProcessLimit(int max) {
4360 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4361 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004362 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004363 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004364 mProcessLimitOverride = max;
4365 }
4366 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 }
4368
4369 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004370 synchronized (this) {
4371 return mProcessLimitOverride;
4372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 }
4374
4375 void foregroundTokenDied(ForegroundToken token) {
4376 synchronized (ActivityManagerService.this) {
4377 synchronized (mPidsSelfLocked) {
4378 ForegroundToken cur
4379 = mForegroundProcesses.get(token.pid);
4380 if (cur != token) {
4381 return;
4382 }
4383 mForegroundProcesses.remove(token.pid);
4384 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4385 if (pr == null) {
4386 return;
4387 }
4388 pr.forcingToForeground = null;
4389 pr.foregroundServices = false;
4390 }
4391 updateOomAdjLocked();
4392 }
4393 }
4394
4395 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4396 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4397 "setProcessForeground()");
4398 synchronized(this) {
4399 boolean changed = false;
4400
4401 synchronized (mPidsSelfLocked) {
4402 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004403 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004404 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 return;
4406 }
4407 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4408 if (oldToken != null) {
4409 oldToken.token.unlinkToDeath(oldToken, 0);
4410 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004411 if (pr != null) {
4412 pr.forcingToForeground = null;
4413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 changed = true;
4415 }
4416 if (isForeground && token != null) {
4417 ForegroundToken newToken = new ForegroundToken() {
4418 public void binderDied() {
4419 foregroundTokenDied(this);
4420 }
4421 };
4422 newToken.pid = pid;
4423 newToken.token = token;
4424 try {
4425 token.linkToDeath(newToken, 0);
4426 mForegroundProcesses.put(pid, newToken);
4427 pr.forcingToForeground = token;
4428 changed = true;
4429 } catch (RemoteException e) {
4430 // If the process died while doing this, we will later
4431 // do the cleanup with the process death link.
4432 }
4433 }
4434 }
4435
4436 if (changed) {
4437 updateOomAdjLocked();
4438 }
4439 }
4440 }
4441
4442 // =========================================================
4443 // PERMISSIONS
4444 // =========================================================
4445
4446 static class PermissionController extends IPermissionController.Stub {
4447 ActivityManagerService mActivityManagerService;
4448 PermissionController(ActivityManagerService activityManagerService) {
4449 mActivityManagerService = activityManagerService;
4450 }
4451
4452 public boolean checkPermission(String permission, int pid, int uid) {
4453 return mActivityManagerService.checkPermission(permission, pid,
4454 uid) == PackageManager.PERMISSION_GRANTED;
4455 }
4456 }
4457
4458 /**
4459 * This can be called with or without the global lock held.
4460 */
4461 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004462 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 // We might be performing an operation on behalf of an indirect binder
4464 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4465 // client identity accordingly before proceeding.
4466 Identity tlsIdentity = sCallerIdentity.get();
4467 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004468 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4470 uid = tlsIdentity.uid;
4471 pid = tlsIdentity.pid;
4472 }
4473
4474 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004475 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 return PackageManager.PERMISSION_GRANTED;
4477 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004478 // Isolated processes don't get any permissions.
4479 if (UserId.isIsolated(uid)) {
4480 return PackageManager.PERMISSION_DENIED;
4481 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004482 // If there is a uid that owns whatever is being accessed, it has
4483 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004484 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004485 return PackageManager.PERMISSION_GRANTED;
4486 }
4487 // If the target is not exported, then nobody else can get to it.
4488 if (!exported) {
4489 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 return PackageManager.PERMISSION_DENIED;
4491 }
4492 if (permission == null) {
4493 return PackageManager.PERMISSION_GRANTED;
4494 }
4495 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004496 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 .checkUidPermission(permission, uid);
4498 } catch (RemoteException e) {
4499 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004500 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 }
4502 return PackageManager.PERMISSION_DENIED;
4503 }
4504
4505 /**
4506 * As the only public entry point for permissions checking, this method
4507 * can enforce the semantic that requesting a check on a null global
4508 * permission is automatically denied. (Internally a null permission
4509 * string is used when calling {@link #checkComponentPermission} in cases
4510 * when only uid-based security is needed.)
4511 *
4512 * This can be called with or without the global lock held.
4513 */
4514 public int checkPermission(String permission, int pid, int uid) {
4515 if (permission == null) {
4516 return PackageManager.PERMISSION_DENIED;
4517 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004518 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 }
4520
4521 /**
4522 * Binder IPC calls go through the public entry point.
4523 * This can be called with or without the global lock held.
4524 */
4525 int checkCallingPermission(String permission) {
4526 return checkPermission(permission,
4527 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004528 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 }
4530
4531 /**
4532 * This can be called with or without the global lock held.
4533 */
4534 void enforceCallingPermission(String permission, String func) {
4535 if (checkCallingPermission(permission)
4536 == PackageManager.PERMISSION_GRANTED) {
4537 return;
4538 }
4539
4540 String msg = "Permission Denial: " + func + " from pid="
4541 + Binder.getCallingPid()
4542 + ", uid=" + Binder.getCallingUid()
4543 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004544 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 throw new SecurityException(msg);
4546 }
4547
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004548 /**
4549 * Determine if UID is holding permissions required to access {@link Uri} in
4550 * the given {@link ProviderInfo}. Final permission checking is always done
4551 * in {@link ContentProvider}.
4552 */
4553 private final boolean checkHoldingPermissionsLocked(
4554 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004555 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4556 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004557
4558 if (pi.applicationInfo.uid == uid) {
4559 return true;
4560 } else if (!pi.exported) {
4561 return false;
4562 }
4563
4564 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4565 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004567 // check if target holds top-level <provider> permissions
4568 if (!readMet && pi.readPermission != null
4569 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4570 readMet = true;
4571 }
4572 if (!writeMet && pi.writePermission != null
4573 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4574 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004576
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004577 // track if unprotected read/write is allowed; any denied
4578 // <path-permission> below removes this ability
4579 boolean allowDefaultRead = pi.readPermission == null;
4580 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004581
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004582 // check if target holds any <path-permission> that match uri
4583 final PathPermission[] pps = pi.pathPermissions;
4584 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004585 final String path = uri.getPath();
4586 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004587 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004588 i--;
4589 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004590 if (pp.match(path)) {
4591 if (!readMet) {
4592 final String pprperm = pp.getReadPermission();
4593 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4594 + pprperm + " for " + pp.getPath()
4595 + ": match=" + pp.match(path)
4596 + " check=" + pm.checkUidPermission(pprperm, uid));
4597 if (pprperm != null) {
4598 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4599 readMet = true;
4600 } else {
4601 allowDefaultRead = false;
4602 }
4603 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004604 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004605 if (!writeMet) {
4606 final String ppwperm = pp.getWritePermission();
4607 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4608 + ppwperm + " for " + pp.getPath()
4609 + ": match=" + pp.match(path)
4610 + " check=" + pm.checkUidPermission(ppwperm, uid));
4611 if (ppwperm != null) {
4612 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4613 writeMet = true;
4614 } else {
4615 allowDefaultWrite = false;
4616 }
4617 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004618 }
4619 }
4620 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004621 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004622
4623 // grant unprotected <provider> read/write, if not blocked by
4624 // <path-permission> above
4625 if (allowDefaultRead) readMet = true;
4626 if (allowDefaultWrite) writeMet = true;
4627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 } catch (RemoteException e) {
4629 return false;
4630 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004631
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004632 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 }
4634
4635 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4636 int modeFlags) {
4637 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004638 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 return true;
4640 }
4641 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4642 if (perms == null) return false;
4643 UriPermission perm = perms.get(uri);
4644 if (perm == null) return false;
4645 return (modeFlags&perm.modeFlags) == modeFlags;
4646 }
4647
4648 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004649 enforceNotIsolatedCaller("checkUriPermission");
4650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 // Another redirected-binder-call permissions check as in
4652 // {@link checkComponentPermission}.
4653 Identity tlsIdentity = sCallerIdentity.get();
4654 if (tlsIdentity != null) {
4655 uid = tlsIdentity.uid;
4656 pid = tlsIdentity.pid;
4657 }
4658
Amith Yamasani742a6712011-05-04 14:49:28 -07004659 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 // Our own process gets to do everything.
4661 if (pid == MY_PID) {
4662 return PackageManager.PERMISSION_GRANTED;
4663 }
4664 synchronized(this) {
4665 return checkUriPermissionLocked(uri, uid, modeFlags)
4666 ? PackageManager.PERMISSION_GRANTED
4667 : PackageManager.PERMISSION_DENIED;
4668 }
4669 }
4670
Dianne Hackborn39792d22010-08-19 18:01:52 -07004671 /**
4672 * Check if the targetPkg can be granted permission to access uri by
4673 * the callingUid using the given modeFlags. Throws a security exception
4674 * if callingUid is not allowed to do this. Returns the uid of the target
4675 * if the URI permission grant should be performed; returns -1 if it is not
4676 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004677 * If you already know the uid of the target, you can supply it in
4678 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004679 */
4680 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004681 Uri uri, int modeFlags, int lastTargetUid) {
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
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004720 int targetUid = lastTargetUid;
4721 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004722 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 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 }
4733
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004734 if (targetUid >= 0) {
4735 // First... does the target actually need this permission?
4736 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4737 // No need to grant the target this permission.
4738 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4739 "Target " + targetPkg + " already has full permission to " + uri);
4740 return -1;
4741 }
4742 } else {
4743 // First... there is no target package, so can anyone access it?
4744 boolean allowed = pi.exported;
4745 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4746 if (pi.readPermission != null) {
4747 allowed = false;
4748 }
4749 }
4750 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4751 if (pi.writePermission != null) {
4752 allowed = false;
4753 }
4754 }
4755 if (allowed) {
4756 return -1;
4757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 }
4759
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004760 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 if (!pi.grantUriPermissions) {
4762 throw new SecurityException("Provider " + pi.packageName
4763 + "/" + pi.name
4764 + " does not allow granting of Uri permissions (uri "
4765 + uri + ")");
4766 }
4767 if (pi.uriPermissionPatterns != null) {
4768 final int N = pi.uriPermissionPatterns.length;
4769 boolean allowed = false;
4770 for (int i=0; i<N; i++) {
4771 if (pi.uriPermissionPatterns[i] != null
4772 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4773 allowed = true;
4774 break;
4775 }
4776 }
4777 if (!allowed) {
4778 throw new SecurityException("Provider " + pi.packageName
4779 + "/" + pi.name
4780 + " does not allow granting of permission to path of Uri "
4781 + uri);
4782 }
4783 }
4784
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004785 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004786 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004787 if (callingUid != Process.myUid()) {
4788 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4789 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4790 throw new SecurityException("Uid " + callingUid
4791 + " does not have permission to uri " + uri);
4792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
4794 }
4795
Dianne Hackborn39792d22010-08-19 18:01:52 -07004796 return targetUid;
4797 }
4798
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004799 public int checkGrantUriPermission(int callingUid, String targetPkg,
4800 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004801 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004802 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004803 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004804 }
4805 }
4806
Dianne Hackborn39792d22010-08-19 18:01:52 -07004807 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4808 Uri uri, int modeFlags, UriPermissionOwner owner) {
4809 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4810 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4811 if (modeFlags == 0) {
4812 return;
4813 }
4814
4815 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 // to the uri, and the target doesn't. Let's now give this to
4817 // the target.
4818
Joe Onorato8a9b2202010-02-26 18:56:32 -08004819 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004820 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 HashMap<Uri, UriPermission> targetUris
4823 = mGrantedUriPermissions.get(targetUid);
4824 if (targetUris == null) {
4825 targetUris = new HashMap<Uri, UriPermission>();
4826 mGrantedUriPermissions.put(targetUid, targetUris);
4827 }
4828
4829 UriPermission perm = targetUris.get(uri);
4830 if (perm == null) {
4831 perm = new UriPermission(targetUid, uri);
4832 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004836 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004838 } else {
4839 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4840 perm.readOwners.add(owner);
4841 owner.addReadPermission(perm);
4842 }
4843 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4844 perm.writeOwners.add(owner);
4845 owner.addWritePermission(perm);
4846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 }
4848 }
4849
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004850 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4851 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004852 if (targetPkg == null) {
4853 throw new NullPointerException("targetPkg");
4854 }
4855
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004856 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004857 if (targetUid < 0) {
4858 return;
4859 }
4860
4861 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4862 }
4863
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004864 static class NeededUriGrants extends ArrayList<Uri> {
4865 final String targetPkg;
4866 final int targetUid;
4867 final int flags;
4868
4869 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4870 targetPkg = _targetPkg;
4871 targetUid = _targetUid;
4872 flags = _flags;
4873 }
4874 }
4875
Dianne Hackborn39792d22010-08-19 18:01:52 -07004876 /**
4877 * Like checkGrantUriPermissionLocked, but takes an Intent.
4878 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004879 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4880 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004881 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004882 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4883 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004884 + " from " + intent + "; flags=0x"
4885 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4886
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004887 if (targetPkg == null) {
4888 throw new NullPointerException("targetPkg");
4889 }
4890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004892 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 }
4894 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004895 ClipData clip = intent.getClipData();
4896 if (data == null && clip == null) {
4897 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004898 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004899 if (data != null) {
4900 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4901 mode, needed != null ? needed.targetUid : -1);
4902 if (target > 0) {
4903 if (needed == null) {
4904 needed = new NeededUriGrants(targetPkg, target, mode);
4905 }
4906 needed.add(data);
4907 }
4908 }
4909 if (clip != null) {
4910 for (int i=0; i<clip.getItemCount(); i++) {
4911 Uri uri = clip.getItemAt(i).getUri();
4912 if (uri != null) {
4913 int target = -1;
4914 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
4915 mode, needed != null ? needed.targetUid : -1);
4916 if (target > 0) {
4917 if (needed == null) {
4918 needed = new NeededUriGrants(targetPkg, target, mode);
4919 }
4920 needed.add(uri);
4921 }
4922 } else {
4923 Intent clipIntent = clip.getItemAt(i).getIntent();
4924 if (clipIntent != null) {
4925 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
4926 callingUid, targetPkg, clipIntent, mode, needed);
4927 if (newNeeded != null) {
4928 needed = newNeeded;
4929 }
4930 }
4931 }
4932 }
4933 }
4934
4935 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004936 }
4937
4938 /**
4939 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4940 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004941 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
4942 UriPermissionOwner owner) {
4943 if (needed != null) {
4944 for (int i=0; i<needed.size(); i++) {
4945 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
4946 needed.get(i), needed.flags, owner);
4947 }
4948 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004949 }
4950
4951 void grantUriPermissionFromIntentLocked(int callingUid,
4952 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004953 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08004954 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004955 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 return;
4957 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004958
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004959 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961
4962 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4963 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004964 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 synchronized(this) {
4966 final ProcessRecord r = getRecordForAppLocked(caller);
4967 if (r == null) {
4968 throw new SecurityException("Unable to find app for caller "
4969 + caller
4970 + " when granting permission to uri " + uri);
4971 }
4972 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004973 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 }
4975 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004976 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004979 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 null);
4981 }
4982 }
4983
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004984 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4986 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4987 HashMap<Uri, UriPermission> perms
4988 = mGrantedUriPermissions.get(perm.uid);
4989 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004990 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004991 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004992 perms.remove(perm.uri);
4993 if (perms.size() == 0) {
4994 mGrantedUriPermissions.remove(perm.uid);
4995 }
4996 }
4997 }
4998 }
4999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5001 int modeFlags) {
5002 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5003 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5004 if (modeFlags == 0) {
5005 return;
5006 }
5007
Joe Onorato8a9b2202010-02-26 18:56:32 -08005008 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005009 "Revoking all granted permissions to " + uri);
5010
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005011 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005012
5013 final String authority = uri.getAuthority();
5014 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005015 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5016 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 if (cpr != null) {
5018 pi = cpr.info;
5019 } else {
5020 try {
5021 pi = pm.resolveContentProvider(authority,
5022 PackageManager.GET_URI_PERMISSION_PATTERNS);
5023 } catch (RemoteException ex) {
5024 }
5025 }
5026 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005027 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 return;
5029 }
5030
5031 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005032 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033 // Right now, if you are not the original owner of the permission,
5034 // you are not allowed to revoke it.
5035 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5036 throw new SecurityException("Uid " + callingUid
5037 + " does not have permission to uri " + uri);
5038 //}
5039 }
5040
5041 // Go through all of the permissions and remove any that match.
5042 final List<String> SEGMENTS = uri.getPathSegments();
5043 if (SEGMENTS != null) {
5044 final int NS = SEGMENTS.size();
5045 int N = mGrantedUriPermissions.size();
5046 for (int i=0; i<N; i++) {
5047 HashMap<Uri, UriPermission> perms
5048 = mGrantedUriPermissions.valueAt(i);
5049 Iterator<UriPermission> it = perms.values().iterator();
5050 toploop:
5051 while (it.hasNext()) {
5052 UriPermission perm = it.next();
5053 Uri targetUri = perm.uri;
5054 if (!authority.equals(targetUri.getAuthority())) {
5055 continue;
5056 }
5057 List<String> targetSegments = targetUri.getPathSegments();
5058 if (targetSegments == null) {
5059 continue;
5060 }
5061 if (targetSegments.size() < NS) {
5062 continue;
5063 }
5064 for (int j=0; j<NS; j++) {
5065 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5066 continue toploop;
5067 }
5068 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005069 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005070 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 perm.clearModes(modeFlags);
5072 if (perm.modeFlags == 0) {
5073 it.remove();
5074 }
5075 }
5076 if (perms.size() == 0) {
5077 mGrantedUriPermissions.remove(
5078 mGrantedUriPermissions.keyAt(i));
5079 N--;
5080 i--;
5081 }
5082 }
5083 }
5084 }
5085
5086 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5087 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005088 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 synchronized(this) {
5090 final ProcessRecord r = getRecordForAppLocked(caller);
5091 if (r == null) {
5092 throw new SecurityException("Unable to find app for caller "
5093 + caller
5094 + " when revoking permission to uri " + uri);
5095 }
5096 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005097 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 return;
5099 }
5100
5101 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5102 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5103 if (modeFlags == 0) {
5104 return;
5105 }
5106
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005107 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108
5109 final String authority = uri.getAuthority();
5110 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005111 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 if (cpr != null) {
5113 pi = cpr.info;
5114 } else {
5115 try {
5116 pi = pm.resolveContentProvider(authority,
5117 PackageManager.GET_URI_PERMISSION_PATTERNS);
5118 } catch (RemoteException ex) {
5119 }
5120 }
5121 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005122 Slog.w(TAG, "No content provider found for permission revoke: "
5123 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 return;
5125 }
5126
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005127 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 }
5129 }
5130
Dianne Hackborn7e269642010-08-25 19:50:20 -07005131 @Override
5132 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005133 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005134 synchronized(this) {
5135 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5136 return owner.getExternalTokenLocked();
5137 }
5138 }
5139
5140 @Override
5141 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5142 Uri uri, int modeFlags) {
5143 synchronized(this) {
5144 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5145 if (owner == null) {
5146 throw new IllegalArgumentException("Unknown owner: " + token);
5147 }
5148 if (fromUid != Binder.getCallingUid()) {
5149 if (Binder.getCallingUid() != Process.myUid()) {
5150 // Only system code can grant URI permissions on behalf
5151 // of other users.
5152 throw new SecurityException("nice try");
5153 }
5154 }
5155 if (targetPkg == null) {
5156 throw new IllegalArgumentException("null target");
5157 }
5158 if (uri == null) {
5159 throw new IllegalArgumentException("null uri");
5160 }
5161
5162 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5163 }
5164 }
5165
5166 @Override
5167 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5168 synchronized(this) {
5169 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5170 if (owner == null) {
5171 throw new IllegalArgumentException("Unknown owner: " + token);
5172 }
5173
5174 if (uri == null) {
5175 owner.removeUriPermissionsLocked(mode);
5176 } else {
5177 owner.removeUriPermissionLocked(uri, mode);
5178 }
5179 }
5180 }
5181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5183 synchronized (this) {
5184 ProcessRecord app =
5185 who != null ? getRecordForAppLocked(who) : null;
5186 if (app == null) return;
5187
5188 Message msg = Message.obtain();
5189 msg.what = WAIT_FOR_DEBUGGER_MSG;
5190 msg.obj = app;
5191 msg.arg1 = waiting ? 1 : 0;
5192 mHandler.sendMessage(msg);
5193 }
5194 }
5195
5196 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005197 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5198 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005200 outInfo.threshold = homeAppMem;
5201 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5202 outInfo.hiddenAppThreshold = hiddenAppMem;
5203 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005204 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005205 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5206 ProcessList.VISIBLE_APP_ADJ);
5207 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5208 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 }
5210
5211 // =========================================================
5212 // TASK MANAGEMENT
5213 // =========================================================
5214
5215 public List getTasks(int maxNum, int flags,
5216 IThumbnailReceiver receiver) {
5217 ArrayList list = new ArrayList();
5218
5219 PendingThumbnailsRecord pending = null;
5220 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005221 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222
5223 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005224 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5226 + ", receiver=" + receiver);
5227
5228 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5229 != PackageManager.PERMISSION_GRANTED) {
5230 if (receiver != null) {
5231 // If the caller wants to wait for pending thumbnails,
5232 // it ain't gonna get them.
5233 try {
5234 receiver.finished();
5235 } catch (RemoteException ex) {
5236 }
5237 }
5238 String msg = "Permission Denial: getTasks() from pid="
5239 + Binder.getCallingPid()
5240 + ", uid=" + Binder.getCallingUid()
5241 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005242 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 throw new SecurityException(msg);
5244 }
5245
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005246 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005247 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005248 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005249 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 TaskRecord curTask = null;
5251 int numActivities = 0;
5252 int numRunning = 0;
5253 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005254 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005256 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257
5258 // Initialize state for next task if needed.
5259 if (top == null ||
5260 (top.state == ActivityState.INITIALIZING
5261 && top.task == r.task)) {
5262 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 curTask = r.task;
5264 numActivities = numRunning = 0;
5265 }
5266
5267 // Add 'r' into the current task.
5268 numActivities++;
5269 if (r.app != null && r.app.thread != null) {
5270 numRunning++;
5271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272
Joe Onorato8a9b2202010-02-26 18:56:32 -08005273 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 TAG, r.intent.getComponent().flattenToShortString()
5275 + ": task=" + r.task);
5276
5277 // If the next one is a different task, generate a new
5278 // TaskInfo entry for what we have.
5279 if (next == null || next.task != curTask) {
5280 ActivityManager.RunningTaskInfo ci
5281 = new ActivityManager.RunningTaskInfo();
5282 ci.id = curTask.taskId;
5283 ci.baseActivity = r.intent.getComponent();
5284 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005285 if (top.thumbHolder != null) {
5286 ci.description = top.thumbHolder.lastDescription;
5287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 ci.numActivities = numActivities;
5289 ci.numRunning = numRunning;
5290 //System.out.println(
5291 // "#" + maxNum + ": " + " descr=" + ci.description);
5292 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005293 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 TAG, "State=" + top.state + "Idle=" + top.idle
5295 + " app=" + top.app
5296 + " thr=" + (top.app != null ? top.app.thread : null));
5297 if (top.state == ActivityState.RESUMED
5298 || top.state == ActivityState.PAUSING) {
5299 if (top.idle && top.app != null
5300 && top.app.thread != null) {
5301 topRecord = top;
5302 topThumbnail = top.app.thread;
5303 } else {
5304 top.thumbnailNeeded = true;
5305 }
5306 }
5307 if (pending == null) {
5308 pending = new PendingThumbnailsRecord(receiver);
5309 }
5310 pending.pendingRecords.add(top);
5311 }
5312 list.add(ci);
5313 maxNum--;
5314 top = null;
5315 }
5316 }
5317
5318 if (pending != null) {
5319 mPendingThumbnails.add(pending);
5320 }
5321 }
5322
Joe Onorato8a9b2202010-02-26 18:56:32 -08005323 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324
5325 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005326 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005328 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005330 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005331 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 }
5333 }
5334
5335 if (pending == null && receiver != null) {
5336 // In this case all thumbnails were available and the client
5337 // is being asked to be told when the remaining ones come in...
5338 // which is unusually, since the top-most currently running
5339 // activity should never have a canned thumbnail! Oh well.
5340 try {
5341 receiver.finished();
5342 } catch (RemoteException ex) {
5343 }
5344 }
5345
5346 return list;
5347 }
5348
5349 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5350 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005351 final int callingUid = Binder.getCallingUid();
5352 // If it's the system uid asking, then use the current user id.
5353 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5354 // require the entire list.
5355 final int callingUserId = callingUid == Process.SYSTEM_UID
5356 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 synchronized (this) {
5358 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5359 "getRecentTasks()");
5360
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005361 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 final int N = mRecentTasks.size();
5364 ArrayList<ActivityManager.RecentTaskInfo> res
5365 = new ArrayList<ActivityManager.RecentTaskInfo>(
5366 maxNum < N ? maxNum : N);
5367 for (int i=0; i<N && maxNum > 0; i++) {
5368 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005369 // Only add calling user's recent tasks
5370 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005371 // Return the entry if desired by the caller. We always return
5372 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005373 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005374 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5375 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005376
Dianne Hackborn905577f2011-09-07 18:31:28 -07005377 if (i == 0
5378 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 || (tr.intent == null)
5380 || ((tr.intent.getFlags()
5381 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5382 ActivityManager.RecentTaskInfo rti
5383 = new ActivityManager.RecentTaskInfo();
5384 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005385 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 rti.baseIntent = new Intent(
5387 tr.intent != null ? tr.intent : tr.affinityIntent);
5388 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005389 rti.description = tr.lastDescription;
5390
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005391 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5392 // Check whether this activity is currently available.
5393 try {
5394 if (rti.origActivity != null) {
5395 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5396 continue;
5397 }
5398 } else if (rti.baseIntent != null) {
5399 if (pm.queryIntentActivities(rti.baseIntent,
5400 null, 0) == null) {
5401 continue;
5402 }
5403 }
5404 } catch (RemoteException e) {
5405 // Will never happen.
5406 }
5407 }
5408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 res.add(rti);
5410 maxNum--;
5411 }
5412 }
5413 return res;
5414 }
5415 }
5416
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005417 private TaskRecord taskForIdLocked(int id) {
5418 final int N = mRecentTasks.size();
5419 for (int i=0; i<N; i++) {
5420 TaskRecord tr = mRecentTasks.get(i);
5421 if (tr.taskId == id) {
5422 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005423 }
5424 }
5425 return null;
5426 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005427
5428 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5429 synchronized (this) {
5430 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5431 "getTaskThumbnails()");
5432 TaskRecord tr = taskForIdLocked(id);
5433 if (tr != null) {
5434 return mMainStack.getTaskThumbnailsLocked(tr);
5435 }
5436 }
5437 return null;
5438 }
5439
5440 public boolean removeSubTask(int taskId, int subTaskIndex) {
5441 synchronized (this) {
5442 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5443 "removeSubTask()");
5444 long ident = Binder.clearCallingIdentity();
5445 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005446 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5447 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005448 } finally {
5449 Binder.restoreCallingIdentity(ident);
5450 }
5451 }
5452 }
5453
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005454 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5455 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005456 Intent baseIntent = new Intent(
5457 tr.intent != null ? tr.intent : tr.affinityIntent);
5458 ComponentName component = baseIntent.getComponent();
5459 if (component == null) {
5460 Slog.w(TAG, "Now component for base intent of task: " + tr);
5461 return;
5462 }
5463
5464 // Find any running services associated with this app.
5465 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005466 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005467 if (sr.packageName.equals(component.getPackageName())) {
5468 services.add(sr);
5469 }
5470 }
5471
5472 // Take care of any running services associated with the app.
5473 for (int i=0; i<services.size(); i++) {
5474 ServiceRecord sr = services.get(i);
5475 if (sr.startRequested) {
5476 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005477 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005478 stopServiceLocked(sr);
5479 } else {
5480 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005481 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005482 if (sr.app != null && sr.app.thread != null) {
5483 sendServiceArgsLocked(sr, false);
5484 }
5485 }
5486 }
5487 }
5488
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005489 if (killProcesses) {
5490 // Find any running processes associated with this app.
5491 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5492 SparseArray<ProcessRecord> appProcs
5493 = mProcessNames.getMap().get(component.getPackageName());
5494 if (appProcs != null) {
5495 for (int i=0; i<appProcs.size(); i++) {
5496 procs.add(appProcs.valueAt(i));
5497 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005498 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005499
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005500 // Kill the running processes.
5501 for (int i=0; i<procs.size(); i++) {
5502 ProcessRecord pr = procs.get(i);
5503 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5504 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5505 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5506 pr.processName, pr.setAdj, "remove task");
5507 Process.killProcessQuiet(pr.pid);
5508 } else {
5509 pr.waitingToKill = "remove task";
5510 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005511 }
5512 }
5513 }
5514
5515 public boolean removeTask(int taskId, int flags) {
5516 synchronized (this) {
5517 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5518 "removeTask()");
5519 long ident = Binder.clearCallingIdentity();
5520 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005521 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5522 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005523 if (r != null) {
5524 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005525 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005526 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005527 } else {
5528 TaskRecord tr = null;
5529 int i=0;
5530 while (i < mRecentTasks.size()) {
5531 TaskRecord t = mRecentTasks.get(i);
5532 if (t.taskId == taskId) {
5533 tr = t;
5534 break;
5535 }
5536 i++;
5537 }
5538 if (tr != null) {
5539 if (tr.numActivities <= 0) {
5540 // Caller is just removing a recent task that is
5541 // not actively running. That is easy!
5542 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005543 cleanUpRemovedTaskLocked(tr, flags);
5544 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005545 } else {
5546 Slog.w(TAG, "removeTask: task " + taskId
5547 + " does not have activities to remove, "
5548 + " but numActivities=" + tr.numActivities
5549 + ": " + tr);
5550 }
5551 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005552 }
5553 } finally {
5554 Binder.restoreCallingIdentity(ident);
5555 }
5556 }
5557 return false;
5558 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5561 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005562 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 TaskRecord jt = startTask;
5564
5565 // First look backwards
5566 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005567 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568 if (r.task != jt) {
5569 jt = r.task;
5570 if (affinity.equals(jt.affinity)) {
5571 return j;
5572 }
5573 }
5574 }
5575
5576 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005577 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005578 jt = startTask;
5579 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005580 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 if (r.task != jt) {
5582 if (affinity.equals(jt.affinity)) {
5583 return j;
5584 }
5585 jt = r.task;
5586 }
5587 }
5588
5589 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005590 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 return N-1;
5592 }
5593
5594 return -1;
5595 }
5596
5597 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005598 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005600 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5602 "moveTaskToFront()");
5603
5604 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005605 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5606 Binder.getCallingUid(), "Task to front")) {
5607 return;
5608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 final long origId = Binder.clearCallingIdentity();
5610 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005611 TaskRecord tr = taskForIdLocked(task);
5612 if (tr != null) {
5613 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5614 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005616 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5617 // Caller wants the home activity moved with it. To accomplish this,
5618 // we'll just move the home task to the top first.
5619 mMainStack.moveHomeToFrontLocked();
5620 }
5621 mMainStack.moveTaskToFrontLocked(tr, null);
5622 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005624 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5625 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005627 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5628 mMainStack.mUserLeaving = true;
5629 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005630 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5631 // Caller wants the home activity moved with it. To accomplish this,
5632 // we'll just move the home task to the top first.
5633 mMainStack.moveHomeToFrontLocked();
5634 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005635 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 return;
5637 }
5638 }
5639 } finally {
5640 Binder.restoreCallingIdentity(origId);
5641 }
5642 }
5643 }
5644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 public void moveTaskToBack(int task) {
5646 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5647 "moveTaskToBack()");
5648
5649 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005650 if (mMainStack.mResumedActivity != null
5651 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005652 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5653 Binder.getCallingUid(), "Task to back")) {
5654 return;
5655 }
5656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005658 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 Binder.restoreCallingIdentity(origId);
5660 }
5661 }
5662
5663 /**
5664 * Moves an activity, and all of the other activities within the same task, to the bottom
5665 * of the history stack. The activity's order within the task is unchanged.
5666 *
5667 * @param token A reference to the activity we wish to move
5668 * @param nonRoot If false then this only works if the activity is the root
5669 * of a task; if true it will work for any activity in a task.
5670 * @return Returns true if the move completed, false if not.
5671 */
5672 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005673 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 synchronized(this) {
5675 final long origId = Binder.clearCallingIdentity();
5676 int taskId = getTaskForActivityLocked(token, !nonRoot);
5677 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005678 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 }
5680 Binder.restoreCallingIdentity(origId);
5681 }
5682 return false;
5683 }
5684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 public void moveTaskBackwards(int task) {
5686 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5687 "moveTaskBackwards()");
5688
5689 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005690 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5691 Binder.getCallingUid(), "Task backwards")) {
5692 return;
5693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 final long origId = Binder.clearCallingIdentity();
5695 moveTaskBackwardsLocked(task);
5696 Binder.restoreCallingIdentity(origId);
5697 }
5698 }
5699
5700 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005701 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 }
5703
5704 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5705 synchronized(this) {
5706 return getTaskForActivityLocked(token, onlyRoot);
5707 }
5708 }
5709
5710 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005711 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 TaskRecord lastTask = null;
5713 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005714 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005715 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 if (!onlyRoot || lastTask != r.task) {
5717 return r.task.taskId;
5718 }
5719 return -1;
5720 }
5721 lastTask = r.task;
5722 }
5723
5724 return -1;
5725 }
5726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 // =========================================================
5728 // THUMBNAILS
5729 // =========================================================
5730
5731 public void reportThumbnail(IBinder token,
5732 Bitmap thumbnail, CharSequence description) {
5733 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5734 final long origId = Binder.clearCallingIdentity();
5735 sendPendingThumbnail(null, token, thumbnail, description, true);
5736 Binder.restoreCallingIdentity(origId);
5737 }
5738
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005739 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 Bitmap thumbnail, CharSequence description, boolean always) {
5741 TaskRecord task = null;
5742 ArrayList receivers = null;
5743
5744 //System.out.println("Send pending thumbnail: " + r);
5745
5746 synchronized(this) {
5747 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005748 r = mMainStack.isInStackLocked(token);
5749 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 return;
5751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005753 if (thumbnail == null && r.thumbHolder != null) {
5754 thumbnail = r.thumbHolder.lastThumbnail;
5755 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 }
5757 if (thumbnail == null && !always) {
5758 // If there is no thumbnail, and this entry is not actually
5759 // going away, then abort for now and pick up the next
5760 // thumbnail we get.
5761 return;
5762 }
5763 task = r.task;
5764
5765 int N = mPendingThumbnails.size();
5766 int i=0;
5767 while (i<N) {
5768 PendingThumbnailsRecord pr =
5769 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5770 //System.out.println("Looking in " + pr.pendingRecords);
5771 if (pr.pendingRecords.remove(r)) {
5772 if (receivers == null) {
5773 receivers = new ArrayList();
5774 }
5775 receivers.add(pr);
5776 if (pr.pendingRecords.size() == 0) {
5777 pr.finished = true;
5778 mPendingThumbnails.remove(i);
5779 N--;
5780 continue;
5781 }
5782 }
5783 i++;
5784 }
5785 }
5786
5787 if (receivers != null) {
5788 final int N = receivers.size();
5789 for (int i=0; i<N; i++) {
5790 try {
5791 PendingThumbnailsRecord pr =
5792 (PendingThumbnailsRecord)receivers.get(i);
5793 pr.receiver.newThumbnail(
5794 task != null ? task.taskId : -1, thumbnail, description);
5795 if (pr.finished) {
5796 pr.receiver.finished();
5797 }
5798 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005799 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 }
5801 }
5802 }
5803 }
5804
5805 // =========================================================
5806 // CONTENT PROVIDERS
5807 // =========================================================
5808
Jeff Brown10e89712011-07-08 18:52:57 -07005809 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5810 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005812 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005813 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005814 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 } catch (RemoteException ex) {
5816 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005817 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005818 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5819 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 if (providers != null) {
5821 final int N = providers.size();
5822 for (int i=0; i<N; i++) {
5823 ProviderInfo cpi =
5824 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005825
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005826 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005827 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005829 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005830 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005832 if (DEBUG_MU)
5833 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 app.pubProviders.put(cpi.name, cpr);
5835 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005836 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
5838 }
5839 return providers;
5840 }
5841
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005842 /**
5843 * Check if {@link ProcessRecord} has a possible chance at accessing the
5844 * given {@link ProviderInfo}. Final permission checking is always done
5845 * in {@link ContentProvider}.
5846 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005848 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005850 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005852 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005853 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 return null;
5855 }
5856 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005857 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 == PackageManager.PERMISSION_GRANTED) {
5859 return null;
5860 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005861
5862 PathPermission[] pps = cpi.pathPermissions;
5863 if (pps != null) {
5864 int i = pps.length;
5865 while (i > 0) {
5866 i--;
5867 PathPermission pp = pps[i];
5868 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005869 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005870 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005871 return null;
5872 }
5873 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005874 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005875 == PackageManager.PERMISSION_GRANTED) {
5876 return null;
5877 }
5878 }
5879 }
5880
Dianne Hackbornb424b632010-08-18 15:59:05 -07005881 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5882 if (perms != null) {
5883 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5884 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5885 return null;
5886 }
5887 }
5888 }
5889
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005890 String msg;
5891 if (!cpi.exported) {
5892 msg = "Permission Denial: opening provider " + cpi.name
5893 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5894 + ", uid=" + callingUid + ") that is not exported from uid "
5895 + cpi.applicationInfo.uid;
5896 } else {
5897 msg = "Permission Denial: opening provider " + cpi.name
5898 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5899 + ", uid=" + callingUid + ") requires "
5900 + cpi.readPermission + " or " + cpi.writePermission;
5901 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005902 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 return msg;
5904 }
5905
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005906 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5907 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005908 if (r != null) {
5909 Integer cnt = r.conProviders.get(cpr);
5910 if (DEBUG_PROVIDER) Slog.v(TAG,
5911 "Adding provider requested by "
5912 + r.processName + " from process "
5913 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5914 + " cnt=" + (cnt == null ? 1 : cnt));
5915 if (cnt == null) {
5916 cpr.clients.add(r);
5917 r.conProviders.put(cpr, new Integer(1));
5918 return true;
5919 } else {
5920 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5921 }
5922 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005923 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005924 }
5925 return false;
5926 }
5927
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005928 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5929 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005930 if (r != null) {
5931 Integer cnt = r.conProviders.get(cpr);
5932 if (DEBUG_PROVIDER) Slog.v(TAG,
5933 "Removing provider requested by "
5934 + r.processName + " from process "
5935 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5936 + " cnt=" + cnt);
5937 if (cnt == null || cnt.intValue() <= 1) {
5938 cpr.clients.remove(r);
5939 r.conProviders.remove(cpr);
5940 return true;
5941 } else {
5942 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5943 }
5944 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005945 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005946 }
5947 return false;
5948 }
5949
Amith Yamasani742a6712011-05-04 14:49:28 -07005950 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005951 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 ContentProviderRecord cpr;
5953 ProviderInfo cpi = null;
5954
5955 synchronized(this) {
5956 ProcessRecord r = null;
5957 if (caller != null) {
5958 r = getRecordForAppLocked(caller);
5959 if (r == null) {
5960 throw new SecurityException(
5961 "Unable to find app for caller " + caller
5962 + " (pid=" + Binder.getCallingPid()
5963 + ") when getting content provider " + name);
5964 }
5965 }
5966
5967 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005968 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005969 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005970 boolean providerRunning = cpr != null;
5971 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005973 String msg;
5974 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5975 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
5977
5978 if (r != null && cpr.canRunHere(r)) {
5979 // This provider has been published or is in the process
5980 // of being published... but it is also allowed to run
5981 // in the caller's process, so don't make a connection
5982 // and just let the caller instantiate its own instance.
5983 if (cpr.provider != null) {
5984 // don't give caller the provider object, it needs
5985 // to make its own.
5986 cpr = new ContentProviderRecord(cpr);
5987 }
5988 return cpr;
5989 }
5990
5991 final long origId = Binder.clearCallingIdentity();
5992
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005993 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005995 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005996 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005997 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005998 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005999 // make sure to count it as being accessed and thus
6000 // back up on the LRU list. This is good because
6001 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006002 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006003 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006004 }
6005
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006006 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006007 if (false) {
6008 if (cpr.name.flattenToShortString().equals(
6009 "com.android.providers.calendar/.CalendarProvider2")) {
6010 Slog.v(TAG, "****************** KILLING "
6011 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006012 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006013 }
6014 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006015 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006016 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6017 // NOTE: there is still a race here where a signal could be
6018 // pending on the process even though we managed to update its
6019 // adj level. Not sure what to do about this, but at least
6020 // the race is now smaller.
6021 if (!success) {
6022 // Uh oh... it looks like the provider's process
6023 // has been killed on us. We need to wait for a new
6024 // process to be started, and make sure its death
6025 // doesn't kill our process.
6026 Slog.i(TAG,
6027 "Existing provider " + cpr.name.flattenToShortString()
6028 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006029 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006030 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006031 if (!lastRef) {
6032 // This wasn't the last ref our process had on
6033 // the provider... we have now been killed, bail.
6034 return null;
6035 }
6036 providerRunning = false;
6037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 }
6039
6040 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006043 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006045 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006046 resolveContentProvider(name,
6047 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 } catch (RemoteException ex) {
6049 }
6050 if (cpi == null) {
6051 return null;
6052 }
6053
Amith Yamasani742a6712011-05-04 14:49:28 -07006054 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6055 Binder.getOrigCallingUser());
6056
Dianne Hackbornb424b632010-08-18 15:59:05 -07006057 String msg;
6058 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6059 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
6061
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006062 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006063 && !cpi.processName.equals("system")) {
6064 // If this content provider does not run in the system
6065 // process, and the system is not yet ready to run other
6066 // processes, then fail fast instead of hanging.
6067 throw new IllegalArgumentException(
6068 "Attempt to launch content provider before system ready");
6069 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006070
6071 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006072 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 final boolean firstClass = cpr == null;
6074 if (firstClass) {
6075 try {
6076 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006077 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 getApplicationInfo(
6079 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006080 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006082 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 + cpi.name);
6084 return null;
6085 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006086 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006087 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 } catch (RemoteException ex) {
6089 // pm is in same process, this will never happen.
6090 }
6091 }
6092
6093 if (r != null && cpr.canRunHere(r)) {
6094 // If this is a multiprocess provider, then just return its
6095 // info and allow the caller to instantiate it. Only do
6096 // this if the provider is the same user as the caller's
6097 // process, or can run as root (so can be in any process).
6098 return cpr;
6099 }
6100
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006101 if (DEBUG_PROVIDER) {
6102 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006103 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006104 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 }
6106
6107 // This is single process, and our app is now connecting to it.
6108 // See if we are already in the process of launching this
6109 // provider.
6110 final int N = mLaunchingProviders.size();
6111 int i;
6112 for (i=0; i<N; i++) {
6113 if (mLaunchingProviders.get(i) == cpr) {
6114 break;
6115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 }
6117
6118 // If the provider is not already being launched, then get it
6119 // started.
6120 if (i >= N) {
6121 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006122
6123 try {
6124 // Content provider is now in use, its package can't be stopped.
6125 try {
6126 AppGlobals.getPackageManager().setPackageStoppedState(
6127 cpr.appInfo.packageName, false);
6128 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006129 } catch (IllegalArgumentException e) {
6130 Slog.w(TAG, "Failed trying to unstop package "
6131 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006132 }
6133
6134 ProcessRecord proc = startProcessLocked(cpi.processName,
6135 cpr.appInfo, false, 0, "content provider",
6136 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006137 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006138 if (proc == null) {
6139 Slog.w(TAG, "Unable to launch app "
6140 + cpi.applicationInfo.packageName + "/"
6141 + cpi.applicationInfo.uid + " for provider "
6142 + name + ": process is bad");
6143 return null;
6144 }
6145 cpr.launchingApp = proc;
6146 mLaunchingProviders.add(cpr);
6147 } finally {
6148 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 }
6151
6152 // Make sure the provider is published (the same provider class
6153 // may be published under multiple names).
6154 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006155 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006157
Amith Yamasani742a6712011-05-04 14:49:28 -07006158 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006159 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 }
6161 }
6162
6163 // Wait for the provider to be published...
6164 synchronized (cpr) {
6165 while (cpr.provider == null) {
6166 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006167 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168 + cpi.applicationInfo.packageName + "/"
6169 + cpi.applicationInfo.uid + " for provider "
6170 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006171 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 cpi.applicationInfo.packageName,
6173 cpi.applicationInfo.uid, name);
6174 return null;
6175 }
6176 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006177 if (DEBUG_MU) {
6178 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6179 + cpr.launchingApp);
6180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 cpr.wait();
6182 } catch (InterruptedException ex) {
6183 }
6184 }
6185 }
6186 return cpr;
6187 }
6188
6189 public final ContentProviderHolder getContentProvider(
6190 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006191 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 if (caller == null) {
6193 String msg = "null IApplicationThread when getting content provider "
6194 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006195 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 throw new SecurityException(msg);
6197 }
6198
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006199 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 }
6201
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006202 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6203 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6204 "Do not have permission in call getContentProviderExternal()");
6205 return getContentProviderExternalUnchecked(name, token);
6206 }
6207
6208 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6209 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 }
6211
6212 /**
6213 * Drop a content provider from a ProcessRecord's bookkeeping
6214 * @param cpr
6215 */
6216 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006217 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006219 int userId = UserId.getUserId(Binder.getCallingUid());
6220 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006222 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006223 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006224 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 return;
6226 }
6227 final ProcessRecord r = getRecordForAppLocked(caller);
6228 if (r == null) {
6229 throw new SecurityException(
6230 "Unable to find app for caller " + caller +
6231 " when removing content provider " + name);
6232 }
6233 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006234 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006235 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6236 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6237 + r.info.processName + " from process "
6238 + localCpr.appInfo.processName);
6239 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006241 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006242 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 return;
6244 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006245 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006246 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 }
6250 }
6251
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006252 public void removeContentProviderExternal(String name, IBinder token) {
6253 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6254 "Do not have permission in call removeContentProviderExternal()");
6255 removeContentProviderExternalUnchecked(name, token);
6256 }
6257
6258 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006260 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6261 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 if(cpr == null) {
6263 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006264 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 return;
6266 }
6267
6268 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006269 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006270 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6271 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006272 if (localCpr.hasExternalProcessHandles()) {
6273 if (localCpr.removeExternalProcessHandleLocked(token)) {
6274 updateOomAdjLocked();
6275 } else {
6276 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6277 + " with no external reference for token: "
6278 + token + ".");
6279 }
6280 } else {
6281 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6282 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 }
6285 }
6286
6287 public final void publishContentProviders(IApplicationThread caller,
6288 List<ContentProviderHolder> providers) {
6289 if (providers == null) {
6290 return;
6291 }
6292
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006293 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 synchronized(this) {
6295 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006296 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006297 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 if (r == null) {
6299 throw new SecurityException(
6300 "Unable to find app for caller " + caller
6301 + " (pid=" + Binder.getCallingPid()
6302 + ") when publishing content providers");
6303 }
6304
6305 final long origId = Binder.clearCallingIdentity();
6306
6307 final int N = providers.size();
6308 for (int i=0; i<N; i++) {
6309 ContentProviderHolder src = providers.get(i);
6310 if (src == null || src.info == null || src.provider == null) {
6311 continue;
6312 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006313 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006314 if (DEBUG_MU)
6315 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006317 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006318 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 String names[] = dst.info.authority.split(";");
6320 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006321 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 }
6323
6324 int NL = mLaunchingProviders.size();
6325 int j;
6326 for (j=0; j<NL; j++) {
6327 if (mLaunchingProviders.get(j) == dst) {
6328 mLaunchingProviders.remove(j);
6329 j--;
6330 NL--;
6331 }
6332 }
6333 synchronized (dst) {
6334 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006335 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 dst.notifyAll();
6337 }
6338 updateOomAdjLocked(r);
6339 }
6340 }
6341
6342 Binder.restoreCallingIdentity(origId);
6343 }
6344 }
6345
6346 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006347 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006348 synchronized (mSelf) {
6349 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6350 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006351 if (providers != null) {
6352 for (int i=providers.size()-1; i>=0; i--) {
6353 ProviderInfo pi = (ProviderInfo)providers.get(i);
6354 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6355 Slog.w(TAG, "Not installing system proc provider " + pi.name
6356 + ": not system .apk");
6357 providers.remove(i);
6358 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006359 }
6360 }
6361 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006362 if (providers != null) {
6363 mSystemThread.installSystemProviders(providers);
6364 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006365
6366 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006367
6368 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 }
6370
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006371 /**
6372 * Allows app to retrieve the MIME type of a URI without having permission
6373 * to access its content provider.
6374 *
6375 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6376 *
6377 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6378 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6379 */
6380 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006381 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006382 final String name = uri.getAuthority();
6383 final long ident = Binder.clearCallingIdentity();
6384 ContentProviderHolder holder = null;
6385
6386 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006387 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006388 if (holder != null) {
6389 return holder.provider.getType(uri);
6390 }
6391 } catch (RemoteException e) {
6392 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6393 return null;
6394 } finally {
6395 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006396 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006397 }
6398 Binder.restoreCallingIdentity(ident);
6399 }
6400
6401 return null;
6402 }
6403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 // =========================================================
6405 // GLOBAL MANAGEMENT
6406 // =========================================================
6407
6408 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006409 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 String proc = customProcess != null ? customProcess : info.processName;
6411 BatteryStatsImpl.Uid.Proc ps = null;
6412 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006413 int uid = info.uid;
6414 if (isolated) {
6415 int userId = UserId.getUserId(uid);
6416 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6417 uid = 0;
6418 while (true) {
6419 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6420 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6421 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6422 }
6423 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6424 mNextIsolatedProcessUid++;
6425 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6426 // No process for this uid, use it.
6427 break;
6428 }
6429 stepsLeft--;
6430 if (stepsLeft <= 0) {
6431 return null;
6432 }
6433 }
6434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 synchronized (stats) {
6436 ps = stats.getProcessStatsLocked(info.uid, proc);
6437 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006438 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
6440
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006441 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6442 ProcessRecord app;
6443 if (!isolated) {
6444 app = getProcessRecordLocked(info.processName, info.uid);
6445 } else {
6446 app = null;
6447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448
6449 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006450 app = newProcessRecordLocked(null, info, null, isolated);
6451 mProcessNames.put(info.processName, app.uid, app);
6452 if (isolated) {
6453 mIsolatedProcesses.put(app.uid, app);
6454 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006455 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 }
6457
Dianne Hackborne7f97212011-02-24 14:40:20 -08006458 // This package really, really can not be stopped.
6459 try {
6460 AppGlobals.getPackageManager().setPackageStoppedState(
6461 info.packageName, false);
6462 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006463 } catch (IllegalArgumentException e) {
6464 Slog.w(TAG, "Failed trying to unstop package "
6465 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006466 }
6467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6469 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6470 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006471 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 }
6473 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6474 mPersistentStartingProcesses.add(app);
6475 startProcessLocked(app, "added application", app.processName);
6476 }
6477
6478 return app;
6479 }
6480
6481 public void unhandledBack() {
6482 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6483 "unhandledBack()");
6484
6485 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006486 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006487 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 TAG, "Performing unhandledBack(): stack size = " + count);
6489 if (count > 1) {
6490 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006491 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6493 Binder.restoreCallingIdentity(origId);
6494 }
6495 }
6496 }
6497
6498 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006499 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006501 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 ParcelFileDescriptor pfd = null;
6503 if (cph != null) {
6504 // We record the binder invoker's uid in thread-local storage before
6505 // going to the content provider to open the file. Later, in the code
6506 // that handles all permissions checks, we look for this uid and use
6507 // that rather than the Activity Manager's own uid. The effect is that
6508 // we do the check against the caller's permissions even though it looks
6509 // to the content provider like the Activity Manager itself is making
6510 // the request.
6511 sCallerIdentity.set(new Identity(
6512 Binder.getCallingPid(), Binder.getCallingUid()));
6513 try {
6514 pfd = cph.provider.openFile(uri, "r");
6515 } catch (FileNotFoundException e) {
6516 // do nothing; pfd will be returned null
6517 } finally {
6518 // Ensure that whatever happens, we clean up the identity state
6519 sCallerIdentity.remove();
6520 }
6521
6522 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006523 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006525 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 }
6527 return pfd;
6528 }
6529
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006530 // Actually is sleeping or shutting down or whatever else in the future
6531 // is an inactive state.
6532 public boolean isSleeping() {
6533 return mSleeping || mShuttingDown;
6534 }
6535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 public void goingToSleep() {
6537 synchronized(this) {
6538 mSleeping = true;
6539 mWindowManager.setEventDispatching(false);
6540
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006541 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006542
6543 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006544 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006545 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6546 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006547 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 }
6549 }
6550
Dianne Hackborn55280a92009-05-07 15:53:46 -07006551 public boolean shutdown(int timeout) {
6552 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6553 != PackageManager.PERMISSION_GRANTED) {
6554 throw new SecurityException("Requires permission "
6555 + android.Manifest.permission.SHUTDOWN);
6556 }
6557
6558 boolean timedout = false;
6559
6560 synchronized(this) {
6561 mShuttingDown = true;
6562 mWindowManager.setEventDispatching(false);
6563
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006564 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006565 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006566 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006567 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006568 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006569 long delay = endTime - System.currentTimeMillis();
6570 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006571 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006572 timedout = true;
6573 break;
6574 }
6575 try {
6576 this.wait();
6577 } catch (InterruptedException e) {
6578 }
6579 }
6580 }
6581 }
6582
6583 mUsageStatsService.shutdown();
6584 mBatteryStatsService.shutdown();
6585
6586 return timedout;
6587 }
6588
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006589 public final void activitySlept(IBinder token) {
6590 if (localLOGV) Slog.v(
6591 TAG, "Activity slept: token=" + token);
6592
6593 ActivityRecord r = null;
6594
6595 final long origId = Binder.clearCallingIdentity();
6596
6597 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006598 r = mMainStack.isInStackLocked(token);
6599 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006600 mMainStack.activitySleptLocked(r);
6601 }
6602 }
6603
6604 Binder.restoreCallingIdentity(origId);
6605 }
6606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 public void wakingUp() {
6608 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 mWindowManager.setEventDispatching(true);
6610 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006611 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006612 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 }
6614 }
6615
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006616 public void stopAppSwitches() {
6617 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6618 != PackageManager.PERMISSION_GRANTED) {
6619 throw new SecurityException("Requires permission "
6620 + android.Manifest.permission.STOP_APP_SWITCHES);
6621 }
6622
6623 synchronized(this) {
6624 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6625 + APP_SWITCH_DELAY_TIME;
6626 mDidAppSwitch = false;
6627 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6628 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6629 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6630 }
6631 }
6632
6633 public void resumeAppSwitches() {
6634 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6635 != PackageManager.PERMISSION_GRANTED) {
6636 throw new SecurityException("Requires permission "
6637 + android.Manifest.permission.STOP_APP_SWITCHES);
6638 }
6639
6640 synchronized(this) {
6641 // Note that we don't execute any pending app switches... we will
6642 // let those wait until either the timeout, or the next start
6643 // activity request.
6644 mAppSwitchesAllowedTime = 0;
6645 }
6646 }
6647
6648 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6649 String name) {
6650 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6651 return true;
6652 }
6653
6654 final int perm = checkComponentPermission(
6655 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006656 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006657 if (perm == PackageManager.PERMISSION_GRANTED) {
6658 return true;
6659 }
6660
Joe Onorato8a9b2202010-02-26 18:56:32 -08006661 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006662 return false;
6663 }
6664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 public void setDebugApp(String packageName, boolean waitForDebugger,
6666 boolean persistent) {
6667 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6668 "setDebugApp()");
6669
6670 // Note that this is not really thread safe if there are multiple
6671 // callers into it at the same time, but that's not a situation we
6672 // care about.
6673 if (persistent) {
6674 final ContentResolver resolver = mContext.getContentResolver();
6675 Settings.System.putString(
6676 resolver, Settings.System.DEBUG_APP,
6677 packageName);
6678 Settings.System.putInt(
6679 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6680 waitForDebugger ? 1 : 0);
6681 }
6682
6683 synchronized (this) {
6684 if (!persistent) {
6685 mOrigDebugApp = mDebugApp;
6686 mOrigWaitForDebugger = mWaitForDebugger;
6687 }
6688 mDebugApp = packageName;
6689 mWaitForDebugger = waitForDebugger;
6690 mDebugTransient = !persistent;
6691 if (packageName != null) {
6692 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006693 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 Binder.restoreCallingIdentity(origId);
6695 }
6696 }
6697 }
6698
Siva Velusamy92a8b222012-03-09 16:24:04 -08006699 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6700 synchronized (this) {
6701 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6702 if (!isDebuggable) {
6703 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6704 throw new SecurityException("Process not debuggable: " + app.packageName);
6705 }
6706 }
6707
6708 mOpenGlTraceApp = processName;
6709 }
6710 }
6711
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006712 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6713 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6714 synchronized (this) {
6715 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6716 if (!isDebuggable) {
6717 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6718 throw new SecurityException("Process not debuggable: " + app.packageName);
6719 }
6720 }
6721 mProfileApp = processName;
6722 mProfileFile = profileFile;
6723 if (mProfileFd != null) {
6724 try {
6725 mProfileFd.close();
6726 } catch (IOException e) {
6727 }
6728 mProfileFd = null;
6729 }
6730 mProfileFd = profileFd;
6731 mProfileType = 0;
6732 mAutoStopProfiler = autoStopProfiler;
6733 }
6734 }
6735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 public void setAlwaysFinish(boolean enabled) {
6737 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6738 "setAlwaysFinish()");
6739
6740 Settings.System.putInt(
6741 mContext.getContentResolver(),
6742 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6743
6744 synchronized (this) {
6745 mAlwaysFinishActivities = enabled;
6746 }
6747 }
6748
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006749 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006751 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006753 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 }
6755 }
6756
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006757 public boolean isUserAMonkey() {
6758 // For now the fact that there is a controller implies
6759 // we have a monkey.
6760 synchronized (this) {
6761 return mController != null;
6762 }
6763 }
6764
Jeff Sharkeya4620792011-05-20 15:29:23 -07006765 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006766 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6767 "registerProcessObserver()");
6768 synchronized (this) {
6769 mProcessObservers.register(observer);
6770 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006771 }
6772
6773 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006774 synchronized (this) {
6775 mProcessObservers.unregister(observer);
6776 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006777 }
6778
Daniel Sandler69a48172010-06-23 16:29:36 -04006779 public void setImmersive(IBinder token, boolean immersive) {
6780 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006781 ActivityRecord r = mMainStack.isInStackLocked(token);
6782 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006783 throw new IllegalArgumentException();
6784 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006785 r.immersive = immersive;
6786 }
6787 }
6788
6789 public boolean isImmersive(IBinder token) {
6790 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006791 ActivityRecord r = mMainStack.isInStackLocked(token);
6792 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006793 throw new IllegalArgumentException();
6794 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006795 return r.immersive;
6796 }
6797 }
6798
6799 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006800 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006801 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006802 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006803 return (r != null) ? r.immersive : false;
6804 }
6805 }
6806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 public final void enterSafeMode() {
6808 synchronized(this) {
6809 // It only makes sense to do this before the system is ready
6810 // and started launching other packages.
6811 if (!mSystemReady) {
6812 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006813 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 } catch (RemoteException e) {
6815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 }
6817 }
6818 }
6819
Jeff Brownb09abc12011-01-13 21:08:27 -08006820 public final void showSafeModeOverlay() {
6821 View v = LayoutInflater.from(mContext).inflate(
6822 com.android.internal.R.layout.safe_mode, null);
6823 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6824 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6825 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6826 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6827 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6828 lp.format = v.getBackground().getOpacity();
6829 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6830 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6831 ((WindowManager)mContext.getSystemService(
6832 Context.WINDOW_SERVICE)).addView(v, lp);
6833 }
6834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 public void noteWakeupAlarm(IIntentSender sender) {
6836 if (!(sender instanceof PendingIntentRecord)) {
6837 return;
6838 }
6839 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6840 synchronized (stats) {
6841 if (mBatteryStatsService.isOnBattery()) {
6842 mBatteryStatsService.enforceCallingPermission();
6843 PendingIntentRecord rec = (PendingIntentRecord)sender;
6844 int MY_UID = Binder.getCallingUid();
6845 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6846 BatteryStatsImpl.Uid.Pkg pkg =
6847 stats.getPackageStatsLocked(uid, rec.key.packageName);
6848 pkg.incWakeupsLocked();
6849 }
6850 }
6851 }
6852
Dianne Hackborn64825172011-03-02 21:32:58 -08006853 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006855 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006857 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 // XXX Note: don't acquire main activity lock here, because the window
6859 // manager calls in with its locks held.
6860
6861 boolean killed = false;
6862 synchronized (mPidsSelfLocked) {
6863 int[] types = new int[pids.length];
6864 int worstType = 0;
6865 for (int i=0; i<pids.length; i++) {
6866 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6867 if (proc != null) {
6868 int type = proc.setAdj;
6869 types[i] = type;
6870 if (type > worstType) {
6871 worstType = type;
6872 }
6873 }
6874 }
6875
Dianne Hackborn64825172011-03-02 21:32:58 -08006876 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006878 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6879 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006880 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006882
6883 // If this is not a secure call, don't let it kill processes that
6884 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006885 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6886 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006887 }
6888
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006889 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006890 for (int i=0; i<pids.length; i++) {
6891 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6892 if (proc == null) {
6893 continue;
6894 }
6895 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006896 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006897 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006898 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6899 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006901 proc.killedBackground = true;
6902 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 }
6904 }
6905 }
6906 return killed;
6907 }
6908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 public final void startRunning(String pkg, String cls, String action,
6910 String data) {
6911 synchronized(this) {
6912 if (mStartRunning) {
6913 return;
6914 }
6915 mStartRunning = true;
6916 mTopComponent = pkg != null && cls != null
6917 ? new ComponentName(pkg, cls) : null;
6918 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6919 mTopData = data;
6920 if (!mSystemReady) {
6921 return;
6922 }
6923 }
6924
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006925 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 }
6927
6928 private void retrieveSettings() {
6929 final ContentResolver resolver = mContext.getContentResolver();
6930 String debugApp = Settings.System.getString(
6931 resolver, Settings.System.DEBUG_APP);
6932 boolean waitForDebugger = Settings.System.getInt(
6933 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6934 boolean alwaysFinishActivities = Settings.System.getInt(
6935 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6936
6937 Configuration configuration = new Configuration();
6938 Settings.System.getConfiguration(resolver, configuration);
6939
6940 synchronized (this) {
6941 mDebugApp = mOrigDebugApp = debugApp;
6942 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6943 mAlwaysFinishActivities = alwaysFinishActivities;
6944 // This happens before any activities are started, so we can
6945 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006946 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006947 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 }
6949 }
6950
6951 public boolean testIsSystemReady() {
6952 // no need to synchronize(this) just to read & return the value
6953 return mSystemReady;
6954 }
6955
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006956 private static File getCalledPreBootReceiversFile() {
6957 File dataDir = Environment.getDataDirectory();
6958 File systemDir = new File(dataDir, "system");
6959 File fname = new File(systemDir, "called_pre_boots.dat");
6960 return fname;
6961 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006962
6963 static final int LAST_DONE_VERSION = 10000;
6964
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006965 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6966 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6967 File file = getCalledPreBootReceiversFile();
6968 FileInputStream fis = null;
6969 try {
6970 fis = new FileInputStream(file);
6971 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006972 int fvers = dis.readInt();
6973 if (fvers == LAST_DONE_VERSION) {
6974 String vers = dis.readUTF();
6975 String codename = dis.readUTF();
6976 String build = dis.readUTF();
6977 if (android.os.Build.VERSION.RELEASE.equals(vers)
6978 && android.os.Build.VERSION.CODENAME.equals(codename)
6979 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6980 int num = dis.readInt();
6981 while (num > 0) {
6982 num--;
6983 String pkg = dis.readUTF();
6984 String cls = dis.readUTF();
6985 lastDoneReceivers.add(new ComponentName(pkg, cls));
6986 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006987 }
6988 }
6989 } catch (FileNotFoundException e) {
6990 } catch (IOException e) {
6991 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6992 } finally {
6993 if (fis != null) {
6994 try {
6995 fis.close();
6996 } catch (IOException e) {
6997 }
6998 }
6999 }
7000 return lastDoneReceivers;
7001 }
7002
7003 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7004 File file = getCalledPreBootReceiversFile();
7005 FileOutputStream fos = null;
7006 DataOutputStream dos = null;
7007 try {
7008 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7009 fos = new FileOutputStream(file);
7010 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007011 dos.writeInt(LAST_DONE_VERSION);
7012 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007013 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007014 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007015 dos.writeInt(list.size());
7016 for (int i=0; i<list.size(); i++) {
7017 dos.writeUTF(list.get(i).getPackageName());
7018 dos.writeUTF(list.get(i).getClassName());
7019 }
7020 } catch (IOException e) {
7021 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7022 file.delete();
7023 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007024 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007025 if (dos != null) {
7026 try {
7027 dos.close();
7028 } catch (IOException e) {
7029 // TODO Auto-generated catch block
7030 e.printStackTrace();
7031 }
7032 }
7033 }
7034 }
7035
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007036 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 synchronized(this) {
7038 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007039 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 return;
7041 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007042
7043 // Check to see if there are any update receivers to run.
7044 if (!mDidUpdate) {
7045 if (mWaitingUpdate) {
7046 return;
7047 }
7048 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7049 List<ResolveInfo> ris = null;
7050 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007051 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007052 intent, null, 0);
7053 } catch (RemoteException e) {
7054 }
7055 if (ris != null) {
7056 for (int i=ris.size()-1; i>=0; i--) {
7057 if ((ris.get(i).activityInfo.applicationInfo.flags
7058 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7059 ris.remove(i);
7060 }
7061 }
7062 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007063
7064 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7065
7066 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007067 for (int i=0; i<ris.size(); i++) {
7068 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007069 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7070 if (lastDoneReceivers.contains(comp)) {
7071 ris.remove(i);
7072 i--;
7073 }
7074 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007075
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007076 for (int i=0; i<ris.size(); i++) {
7077 ActivityInfo ai = ris.get(i).activityInfo;
7078 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7079 doneReceivers.add(comp);
7080 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007081 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007082 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007083 finisher = new IIntentReceiver.Stub() {
7084 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007085 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007086 boolean sticky) {
7087 // The raw IIntentReceiver interface is called
7088 // with the AM lock held, so redispatch to
7089 // execute our code without the lock.
7090 mHandler.post(new Runnable() {
7091 public void run() {
7092 synchronized (ActivityManagerService.this) {
7093 mDidUpdate = true;
7094 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007095 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007096 showBootMessage(mContext.getText(
7097 R.string.android_upgrading_complete),
7098 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007099 systemReady(goingCallback);
7100 }
7101 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007102 }
7103 };
7104 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007105 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007106 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007107 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007108 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007109 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007110 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007111 mWaitingUpdate = true;
7112 }
7113 }
7114 }
7115 if (mWaitingUpdate) {
7116 return;
7117 }
7118 mDidUpdate = true;
7119 }
7120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 mSystemReady = true;
7122 if (!mStartRunning) {
7123 return;
7124 }
7125 }
7126
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007127 ArrayList<ProcessRecord> procsToKill = null;
7128 synchronized(mPidsSelfLocked) {
7129 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7130 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7131 if (!isAllowedWhileBooting(proc.info)){
7132 if (procsToKill == null) {
7133 procsToKill = new ArrayList<ProcessRecord>();
7134 }
7135 procsToKill.add(proc);
7136 }
7137 }
7138 }
7139
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007140 synchronized(this) {
7141 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007142 for (int i=procsToKill.size()-1; i>=0; i--) {
7143 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007144 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007145 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007146 }
7147 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007148
7149 // Now that we have cleaned up any update processes, we
7150 // are ready to start launching real processes and know that
7151 // we won't trample on them any more.
7152 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007153 }
7154
Joe Onorato8a9b2202010-02-26 18:56:32 -08007155 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007156 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 SystemClock.uptimeMillis());
7158
7159 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007160 // Make sure we have no pre-ready processes sitting around.
7161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007162 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7163 ResolveInfo ri = mContext.getPackageManager()
7164 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007165 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 CharSequence errorMsg = null;
7167 if (ri != null) {
7168 ActivityInfo ai = ri.activityInfo;
7169 ApplicationInfo app = ai.applicationInfo;
7170 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7171 mTopAction = Intent.ACTION_FACTORY_TEST;
7172 mTopData = null;
7173 mTopComponent = new ComponentName(app.packageName,
7174 ai.name);
7175 } else {
7176 errorMsg = mContext.getResources().getText(
7177 com.android.internal.R.string.factorytest_not_system);
7178 }
7179 } else {
7180 errorMsg = mContext.getResources().getText(
7181 com.android.internal.R.string.factorytest_no_action);
7182 }
7183 if (errorMsg != null) {
7184 mTopAction = null;
7185 mTopData = null;
7186 mTopComponent = null;
7187 Message msg = Message.obtain();
7188 msg.what = SHOW_FACTORY_ERROR_MSG;
7189 msg.getData().putCharSequence("msg", errorMsg);
7190 mHandler.sendMessage(msg);
7191 }
7192 }
7193 }
7194
7195 retrieveSettings();
7196
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007197 if (goingCallback != null) goingCallback.run();
7198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 synchronized (this) {
7200 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7201 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007202 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007203 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 if (apps != null) {
7205 int N = apps.size();
7206 int i;
7207 for (i=0; i<N; i++) {
7208 ApplicationInfo info
7209 = (ApplicationInfo)apps.get(i);
7210 if (info != null &&
7211 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007212 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 }
7214 }
7215 }
7216 } catch (RemoteException ex) {
7217 // pm is in same process, this will never happen.
7218 }
7219 }
7220
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007221 // Start up initial activity.
7222 mBooting = true;
7223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007225 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 Message msg = Message.obtain();
7227 msg.what = SHOW_UID_ERROR_MSG;
7228 mHandler.sendMessage(msg);
7229 }
7230 } catch (RemoteException e) {
7231 }
7232
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007233 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 }
7235 }
7236
Dan Egnorb7f03672009-12-09 16:22:32 -08007237 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007238 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007240 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007241 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 startAppProblemLocked(app);
7243 app.stopFreezingAllLocked();
7244 return handleAppCrashLocked(app);
7245 }
7246
Dan Egnorb7f03672009-12-09 16:22:32 -08007247 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007248 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007250 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007251 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7252 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 startAppProblemLocked(app);
7254 app.stopFreezingAllLocked();
7255 }
7256
7257 /**
7258 * Generate a process error record, suitable for attachment to a ProcessRecord.
7259 *
7260 * @param app The ProcessRecord in which the error occurred.
7261 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7262 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007263 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007264 * @param shortMsg Short message describing the crash.
7265 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007266 * @param stackTrace Full crash stack trace, may be null.
7267 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 * @return Returns a fully-formed AppErrorStateInfo record.
7269 */
7270 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007271 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 report.condition = condition;
7275 report.processName = app.processName;
7276 report.pid = app.pid;
7277 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007278 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 report.shortMsg = shortMsg;
7280 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007281 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282
7283 return report;
7284 }
7285
Dan Egnor42471dd2010-01-07 17:25:22 -08007286 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 synchronized (this) {
7288 app.crashing = false;
7289 app.crashingReport = null;
7290 app.notResponding = false;
7291 app.notRespondingReport = null;
7292 if (app.anrDialog == fromDialog) {
7293 app.anrDialog = null;
7294 }
7295 if (app.waitDialog == fromDialog) {
7296 app.waitDialog = null;
7297 }
7298 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007299 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007300 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007301 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7302 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007303 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 }
7306 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007307
Dan Egnorb7f03672009-12-09 16:22:32 -08007308 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 long now = SystemClock.uptimeMillis();
7310
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007311 Long crashTime;
7312 if (!app.isolated) {
7313 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7314 } else {
7315 crashTime = null;
7316 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007317 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007318 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007319 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007321 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007322 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007323 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7324 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007326 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007328 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 }
7330 }
7331 if (!app.persistent) {
7332 // We don't want to start this process again until the user
7333 // explicitly does so... but for persistent process, we really
7334 // need to keep it running. If a persistent process is actually
7335 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007336 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007338 if (!app.isolated) {
7339 // XXX We don't have a way to mark isolated processes
7340 // as bad, since they don't have a peristent identity.
7341 mBadProcesses.put(app.info.processName, app.uid, now);
7342 mProcessCrashTimes.remove(app.info.processName, app.uid);
7343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007345 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007346 // Don't let services in this process be restarted and potentially
7347 // annoy the user repeatedly. Unless it is persistent, since those
7348 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007349 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007350 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 return false;
7352 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007353 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007354 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007355 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007356 if (r.app == app) {
7357 // If the top running activity is from this crashing
7358 // process, then terminate it to avoid getting in a loop.
7359 Slog.w(TAG, " Force finishing activity "
7360 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007361 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007362 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007363 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007364 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007365 // stopped, to avoid a situation where one will get
7366 // re-start our crashing activity once it gets resumed again.
7367 index--;
7368 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007369 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007370 if (r.state == ActivityState.RESUMED
7371 || r.state == ActivityState.PAUSING
7372 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007373 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007374 Slog.w(TAG, " Force finishing activity "
7375 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007376 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007377 Activity.RESULT_CANCELED, null, "crashed");
7378 }
7379 }
7380 }
7381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 }
7383
7384 // Bump up the crash count of any services currently running in the proc.
7385 if (app.services.size() != 0) {
7386 // Any services running in the application need to be placed
7387 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007388 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007390 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007391 sr.crashCount++;
7392 }
7393 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007394
7395 // If the crashing process is what we consider to be the "home process" and it has been
7396 // replaced by a third-party app, clear the package preferred activities from packages
7397 // with a home activity running in the process to prevent a repeatedly crashing app
7398 // from blocking the user to manually clear the list.
7399 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7400 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7401 Iterator it = mHomeProcess.activities.iterator();
7402 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007403 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007404 if (r.isHomeActivity) {
7405 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7406 try {
7407 ActivityThread.getPackageManager()
7408 .clearPackagePreferredActivities(r.packageName);
7409 } catch (RemoteException c) {
7410 // pm is in same process, this will never happen.
7411 }
7412 }
7413 }
7414 }
7415
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007416 if (!app.isolated) {
7417 // XXX Can't keep track of crash times for isolated processes,
7418 // because they don't have a perisistent identity.
7419 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7420 }
7421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 return true;
7423 }
7424
7425 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007426 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7427 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 skipCurrentReceiverLocked(app);
7429 }
7430
7431 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007432 for (BroadcastQueue queue : mBroadcastQueues) {
7433 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 }
7435 }
7436
Dan Egnor60d87622009-12-16 16:32:58 -08007437 /**
7438 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7439 * The application process will exit immediately after this call returns.
7440 * @param app object of the crashing app, null for the system server
7441 * @param crashInfo describing the exception
7442 */
7443 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007444 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007445 final String processName = app == null ? "system_server"
7446 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007447
7448 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007449 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007450 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007451 crashInfo.exceptionClassName,
7452 crashInfo.exceptionMessage,
7453 crashInfo.throwFileName,
7454 crashInfo.throwLineNumber);
7455
Jeff Sharkeya353d262011-10-28 11:12:06 -07007456 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007457
7458 crashApplication(r, crashInfo);
7459 }
7460
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007461 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007462 IBinder app,
7463 int violationMask,
7464 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007465 ProcessRecord r = findAppProcess(app, "StrictMode");
7466 if (r == null) {
7467 return;
7468 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007469
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007470 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007471 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007472 boolean logIt = true;
7473 synchronized (mAlreadyLoggedViolatedStacks) {
7474 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7475 logIt = false;
7476 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007477 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007478 // the relative pain numbers, without logging all
7479 // the stack traces repeatedly. We'd want to do
7480 // likewise in the client code, which also does
7481 // dup suppression, before the Binder call.
7482 } else {
7483 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7484 mAlreadyLoggedViolatedStacks.clear();
7485 }
7486 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7487 }
7488 }
7489 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007490 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007491 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007492 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007493
7494 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7495 AppErrorResult result = new AppErrorResult();
7496 synchronized (this) {
7497 final long origId = Binder.clearCallingIdentity();
7498
7499 Message msg = Message.obtain();
7500 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7501 HashMap<String, Object> data = new HashMap<String, Object>();
7502 data.put("result", result);
7503 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007504 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007505 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007506 msg.obj = data;
7507 mHandler.sendMessage(msg);
7508
7509 Binder.restoreCallingIdentity(origId);
7510 }
7511 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007512 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007513 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007514 }
7515
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007516 // Depending on the policy in effect, there could be a bunch of
7517 // these in quick succession so we try to batch these together to
7518 // minimize disk writes, number of dropbox entries, and maximize
7519 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007520 private void logStrictModeViolationToDropBox(
7521 ProcessRecord process,
7522 StrictMode.ViolationInfo info) {
7523 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007524 return;
7525 }
7526 final boolean isSystemApp = process == null ||
7527 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7528 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007529 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007530 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7531 final DropBoxManager dbox = (DropBoxManager)
7532 mContext.getSystemService(Context.DROPBOX_SERVICE);
7533
7534 // Exit early if the dropbox isn't configured to accept this report type.
7535 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7536
7537 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007538 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007539 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7540 synchronized (sb) {
7541 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007542 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007543 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7544 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007545 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7546 if (info.violationNumThisLoop != 0) {
7547 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7548 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007549 if (info.numAnimationsRunning != 0) {
7550 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7551 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007552 if (info.broadcastIntentAction != null) {
7553 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7554 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007555 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007556 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007557 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007558 if (info.numInstances != -1) {
7559 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7560 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007561 if (info.tags != null) {
7562 for (String tag : info.tags) {
7563 sb.append("Span-Tag: ").append(tag).append("\n");
7564 }
7565 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007566 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007567 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7568 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007569 }
7570 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007571
7572 // Only buffer up to ~64k. Various logging bits truncate
7573 // things at 128k.
7574 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007575 }
7576
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007577 // Flush immediately if the buffer's grown too large, or this
7578 // is a non-system app. Non-system apps are isolated with a
7579 // different tag & policy and not batched.
7580 //
7581 // Batching is useful during internal testing with
7582 // StrictMode settings turned up high. Without batching,
7583 // thousands of separate files could be created on boot.
7584 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007585 new Thread("Error dump: " + dropboxTag) {
7586 @Override
7587 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007588 String report;
7589 synchronized (sb) {
7590 report = sb.toString();
7591 sb.delete(0, sb.length());
7592 sb.trimToSize();
7593 }
7594 if (report.length() != 0) {
7595 dbox.addText(dropboxTag, report);
7596 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007597 }
7598 }.start();
7599 return;
7600 }
7601
7602 // System app batching:
7603 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007604 // An existing dropbox-writing thread is outstanding, so
7605 // we don't need to start it up. The existing thread will
7606 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007607 return;
7608 }
7609
7610 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7611 // (After this point, we shouldn't access AMS internal data structures.)
7612 new Thread("Error dump: " + dropboxTag) {
7613 @Override
7614 public void run() {
7615 // 5 second sleep to let stacks arrive and be batched together
7616 try {
7617 Thread.sleep(5000); // 5 seconds
7618 } catch (InterruptedException e) {}
7619
7620 String errorReport;
7621 synchronized (mStrictModeBuffer) {
7622 errorReport = mStrictModeBuffer.toString();
7623 if (errorReport.length() == 0) {
7624 return;
7625 }
7626 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7627 mStrictModeBuffer.trimToSize();
7628 }
7629 dbox.addText(dropboxTag, errorReport);
7630 }
7631 }.start();
7632 }
7633
Dan Egnor60d87622009-12-16 16:32:58 -08007634 /**
7635 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7636 * @param app object of the crashing app, null for the system server
7637 * @param tag reported by the caller
7638 * @param crashInfo describing the context of the error
7639 * @return true if the process should exit immediately (WTF is fatal)
7640 */
7641 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007642 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007643 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007644 final String processName = app == null ? "system_server"
7645 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007646
7647 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007648 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007649 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007650 tag, crashInfo.exceptionMessage);
7651
Jeff Sharkeya353d262011-10-28 11:12:06 -07007652 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007653
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007654 if (r != null && r.pid != Process.myPid() &&
7655 Settings.Secure.getInt(mContext.getContentResolver(),
7656 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007657 crashApplication(r, crashInfo);
7658 return true;
7659 } else {
7660 return false;
7661 }
7662 }
7663
7664 /**
7665 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7666 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7667 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007668 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007669 if (app == null) {
7670 return null;
7671 }
7672
7673 synchronized (this) {
7674 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7675 final int NA = apps.size();
7676 for (int ia=0; ia<NA; ia++) {
7677 ProcessRecord p = apps.valueAt(ia);
7678 if (p.thread != null && p.thread.asBinder() == app) {
7679 return p;
7680 }
7681 }
7682 }
7683
Dianne Hackborncb44d962011-03-10 17:02:27 -08007684 Slog.w(TAG, "Can't find mystery application for " + reason
7685 + " from pid=" + Binder.getCallingPid()
7686 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007687 return null;
7688 }
7689 }
7690
7691 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007692 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7693 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007694 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007695 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7696 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007697 // Watchdog thread ends up invoking this function (with
7698 // a null ProcessRecord) to add the stack file to dropbox.
7699 // Do not acquire a lock on this (am) in such cases, as it
7700 // could cause a potential deadlock, if and when watchdog
7701 // is invoked due to unavailability of lock on am and it
7702 // would prevent watchdog from killing system_server.
7703 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007704 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007705 return;
7706 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007707 // Note: ProcessRecord 'process' is guarded by the service
7708 // instance. (notably process.pkgList, which could otherwise change
7709 // concurrently during execution of this method)
7710 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007711 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007712 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007713 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007714 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7715 for (String pkg : process.pkgList) {
7716 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007717 try {
Dan Egnora455d192010-03-12 08:52:28 -08007718 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7719 if (pi != null) {
7720 sb.append(" v").append(pi.versionCode);
7721 if (pi.versionName != null) {
7722 sb.append(" (").append(pi.versionName).append(")");
7723 }
7724 }
7725 } catch (RemoteException e) {
7726 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007727 }
Dan Egnora455d192010-03-12 08:52:28 -08007728 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007729 }
Dan Egnora455d192010-03-12 08:52:28 -08007730 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007731 }
7732
7733 private static String processClass(ProcessRecord process) {
7734 if (process == null || process.pid == MY_PID) {
7735 return "system_server";
7736 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7737 return "system_app";
7738 } else {
7739 return "data_app";
7740 }
7741 }
7742
7743 /**
7744 * Write a description of an error (crash, WTF, ANR) to the drop box.
7745 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7746 * @param process which caused the error, null means the system server
7747 * @param activity which triggered the error, null if unknown
7748 * @param parent activity related to the error, null if unknown
7749 * @param subject line related to the error, null if absent
7750 * @param report in long form describing the error, null if absent
7751 * @param logFile to include in the report, null if none
7752 * @param crashInfo giving an application stack trace, null if absent
7753 */
7754 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007755 ProcessRecord process, String processName, ActivityRecord activity,
7756 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007757 final String report, final File logFile,
7758 final ApplicationErrorReport.CrashInfo crashInfo) {
7759 // NOTE -- this must never acquire the ActivityManagerService lock,
7760 // otherwise the watchdog may be prevented from resetting the system.
7761
7762 final String dropboxTag = processClass(process) + "_" + eventType;
7763 final DropBoxManager dbox = (DropBoxManager)
7764 mContext.getSystemService(Context.DROPBOX_SERVICE);
7765
7766 // Exit early if the dropbox isn't configured to accept this report type.
7767 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7768
7769 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007770 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007771 if (activity != null) {
7772 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7773 }
7774 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7775 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7776 }
7777 if (parent != null && parent != activity) {
7778 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7779 }
7780 if (subject != null) {
7781 sb.append("Subject: ").append(subject).append("\n");
7782 }
7783 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007784 if (Debug.isDebuggerConnected()) {
7785 sb.append("Debugger: Connected\n");
7786 }
Dan Egnora455d192010-03-12 08:52:28 -08007787 sb.append("\n");
7788
7789 // Do the rest in a worker thread to avoid blocking the caller on I/O
7790 // (After this point, we shouldn't access AMS internal data structures.)
7791 Thread worker = new Thread("Error dump: " + dropboxTag) {
7792 @Override
7793 public void run() {
7794 if (report != null) {
7795 sb.append(report);
7796 }
7797 if (logFile != null) {
7798 try {
7799 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7800 } catch (IOException e) {
7801 Slog.e(TAG, "Error reading " + logFile, e);
7802 }
7803 }
7804 if (crashInfo != null && crashInfo.stackTrace != null) {
7805 sb.append(crashInfo.stackTrace);
7806 }
7807
7808 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7809 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7810 if (lines > 0) {
7811 sb.append("\n");
7812
7813 // Merge several logcat streams, and take the last N lines
7814 InputStreamReader input = null;
7815 try {
7816 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7817 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7818 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7819
7820 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7821 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7822 input = new InputStreamReader(logcat.getInputStream());
7823
7824 int num;
7825 char[] buf = new char[8192];
7826 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7827 } catch (IOException e) {
7828 Slog.e(TAG, "Error running logcat", e);
7829 } finally {
7830 if (input != null) try { input.close(); } catch (IOException e) {}
7831 }
7832 }
7833
7834 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007835 }
Dan Egnora455d192010-03-12 08:52:28 -08007836 };
7837
7838 if (process == null || process.pid == MY_PID) {
7839 worker.run(); // We may be about to die -- need to run this synchronously
7840 } else {
7841 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007842 }
7843 }
7844
7845 /**
7846 * Bring up the "unexpected error" dialog box for a crashing app.
7847 * Deal with edge cases (intercepts from instrumented applications,
7848 * ActivityController, error intent receivers, that sort of thing).
7849 * @param r the application crashing
7850 * @param crashInfo describing the failure
7851 */
7852 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007853 long timeMillis = System.currentTimeMillis();
7854 String shortMsg = crashInfo.exceptionClassName;
7855 String longMsg = crashInfo.exceptionMessage;
7856 String stackTrace = crashInfo.stackTrace;
7857 if (shortMsg != null && longMsg != null) {
7858 longMsg = shortMsg + ": " + longMsg;
7859 } else if (shortMsg != null) {
7860 longMsg = shortMsg;
7861 }
7862
Dan Egnor60d87622009-12-16 16:32:58 -08007863 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007865 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 try {
7867 String name = r != null ? r.processName : null;
7868 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007869 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007870 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007871 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 + " at watcher's request");
7873 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007874 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875 }
7876 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007877 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 }
7879 }
7880
7881 final long origId = Binder.clearCallingIdentity();
7882
7883 // If this process is running instrumentation, finish it.
7884 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007885 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007887 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7888 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 Bundle info = new Bundle();
7890 info.putString("shortMsg", shortMsg);
7891 info.putString("longMsg", longMsg);
7892 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7893 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007894 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 }
7896
Dan Egnor60d87622009-12-16 16:32:58 -08007897 // If we can't identify the process or it's already exceeded its crash quota,
7898 // quit right away without showing a crash dialog.
7899 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007901 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 }
7903
7904 Message msg = Message.obtain();
7905 msg.what = SHOW_ERROR_MSG;
7906 HashMap data = new HashMap();
7907 data.put("result", result);
7908 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 msg.obj = data;
7910 mHandler.sendMessage(msg);
7911
7912 Binder.restoreCallingIdentity(origId);
7913 }
7914
7915 int res = result.get();
7916
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007917 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007919 if (r != null && !r.isolated) {
7920 // XXX Can't keep track of crash time for isolated processes,
7921 // since they don't have a persistent identity.
7922 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 SystemClock.uptimeMillis());
7924 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007925 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007926 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007927 }
7928 }
7929
7930 if (appErrorIntent != null) {
7931 try {
7932 mContext.startActivity(appErrorIntent);
7933 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007934 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007938
7939 Intent createAppErrorIntentLocked(ProcessRecord r,
7940 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7941 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007942 if (report == null) {
7943 return null;
7944 }
7945 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7946 result.setComponent(r.errorReportReceiver);
7947 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7948 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7949 return result;
7950 }
7951
Dan Egnorb7f03672009-12-09 16:22:32 -08007952 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7953 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007954 if (r.errorReportReceiver == null) {
7955 return null;
7956 }
7957
7958 if (!r.crashing && !r.notResponding) {
7959 return null;
7960 }
7961
Dan Egnorb7f03672009-12-09 16:22:32 -08007962 ApplicationErrorReport report = new ApplicationErrorReport();
7963 report.packageName = r.info.packageName;
7964 report.installerPackageName = r.errorReportReceiver.getPackageName();
7965 report.processName = r.processName;
7966 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007967 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007968
Dan Egnorb7f03672009-12-09 16:22:32 -08007969 if (r.crashing) {
7970 report.type = ApplicationErrorReport.TYPE_CRASH;
7971 report.crashInfo = crashInfo;
7972 } else if (r.notResponding) {
7973 report.type = ApplicationErrorReport.TYPE_ANR;
7974 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007975
Dan Egnorb7f03672009-12-09 16:22:32 -08007976 report.anrInfo.activity = r.notRespondingReport.tag;
7977 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7978 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007979 }
7980
Dan Egnorb7f03672009-12-09 16:22:32 -08007981 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007982 }
7983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007985 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 // assume our apps are happy - lazy create the list
7987 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7988
7989 synchronized (this) {
7990
7991 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007992 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7993 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7995 // This one's in trouble, so we'll generate a report for it
7996 // crashes are higher priority (in case there's a crash *and* an anr)
7997 ActivityManager.ProcessErrorStateInfo report = null;
7998 if (app.crashing) {
7999 report = app.crashingReport;
8000 } else if (app.notResponding) {
8001 report = app.notRespondingReport;
8002 }
8003
8004 if (report != null) {
8005 if (errList == null) {
8006 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8007 }
8008 errList.add(report);
8009 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008010 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008011 " crashing = " + app.crashing +
8012 " notResponding = " + app.notResponding);
8013 }
8014 }
8015 }
8016 }
8017
8018 return errList;
8019 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008020
8021 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008022 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008023 if (currApp != null) {
8024 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8025 }
8026 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008027 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8028 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008029 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8030 if (currApp != null) {
8031 currApp.lru = 0;
8032 }
8033 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008034 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008035 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8036 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8037 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8038 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8039 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8040 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8041 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8042 } else {
8043 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8044 }
8045 }
8046
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008047 private void fillInProcMemInfo(ProcessRecord app,
8048 ActivityManager.RunningAppProcessInfo outInfo) {
8049 outInfo.pid = app.pid;
8050 outInfo.uid = app.info.uid;
8051 if (mHeavyWeightProcess == app) {
8052 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8053 }
8054 if (app.persistent) {
8055 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8056 }
8057 outInfo.lastTrimLevel = app.trimMemoryLevel;
8058 int adj = app.curAdj;
8059 outInfo.importance = oomAdjToImportance(adj, outInfo);
8060 outInfo.importanceReasonCode = app.adjTypeCode;
8061 }
8062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008064 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 // Lazy instantiation of list
8066 List<ActivityManager.RunningAppProcessInfo> runList = null;
8067 synchronized (this) {
8068 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008069 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8070 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8072 // Generate process state info for running application
8073 ActivityManager.RunningAppProcessInfo currApp =
8074 new ActivityManager.RunningAppProcessInfo(app.processName,
8075 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008076 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008077 if (app.adjSource instanceof ProcessRecord) {
8078 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008079 currApp.importanceReasonImportance = oomAdjToImportance(
8080 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008081 } else if (app.adjSource instanceof ActivityRecord) {
8082 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008083 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8084 }
8085 if (app.adjTarget instanceof ComponentName) {
8086 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8087 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008088 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 // + " lru=" + currApp.lru);
8090 if (runList == null) {
8091 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8092 }
8093 runList.add(currApp);
8094 }
8095 }
8096 }
8097 return runList;
8098 }
8099
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008100 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008101 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008102 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8103 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8104 if (runningApps != null && runningApps.size() > 0) {
8105 Set<String> extList = new HashSet<String>();
8106 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8107 if (app.pkgList != null) {
8108 for (String pkg : app.pkgList) {
8109 extList.add(pkg);
8110 }
8111 }
8112 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008113 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008114 for (String pkg : extList) {
8115 try {
8116 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8117 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8118 retList.add(info);
8119 }
8120 } catch (RemoteException e) {
8121 }
8122 }
8123 }
8124 return retList;
8125 }
8126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008127 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008128 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8129 enforceNotIsolatedCaller("getMyMemoryState");
8130 synchronized (this) {
8131 ProcessRecord proc;
8132 synchronized (mPidsSelfLocked) {
8133 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8134 }
8135 fillInProcMemInfo(proc, outInfo);
8136 }
8137 }
8138
8139 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008141 if (checkCallingPermission(android.Manifest.permission.DUMP)
8142 != PackageManager.PERMISSION_GRANTED) {
8143 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8144 + Binder.getCallingPid()
8145 + ", uid=" + Binder.getCallingUid()
8146 + " without permission "
8147 + android.Manifest.permission.DUMP);
8148 return;
8149 }
8150
8151 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008152 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008153 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008154
8155 int opti = 0;
8156 while (opti < args.length) {
8157 String opt = args[opti];
8158 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8159 break;
8160 }
8161 opti++;
8162 if ("-a".equals(opt)) {
8163 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008164 } else if ("-c".equals(opt)) {
8165 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008166 } else if ("-h".equals(opt)) {
8167 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008168 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008169 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008170 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008171 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8172 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8173 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008174 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008175 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008176 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008177 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008178 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008179 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008180 pw.println(" all: dump all activities");
8181 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008182 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008183 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8184 pw.println(" a partial substring in a component name, a");
8185 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008186 pw.println(" -a: include all available server state.");
8187 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008188 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008189 } else {
8190 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008192 }
8193
8194 // Is the caller requesting to dump a particular piece of data?
8195 if (opti < args.length) {
8196 String cmd = args[opti];
8197 opti++;
8198 if ("activities".equals(cmd) || "a".equals(cmd)) {
8199 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008200 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008201 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008202 return;
8203 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008204 String[] newArgs;
8205 String name;
8206 if (opti >= args.length) {
8207 name = null;
8208 newArgs = EMPTY_STRING_ARRAY;
8209 } else {
8210 name = args[opti];
8211 opti++;
8212 newArgs = new String[args.length - opti];
8213 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8214 args.length - opti);
8215 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008216 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008217 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008218 }
8219 return;
8220 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008221 String[] newArgs;
8222 String name;
8223 if (opti >= args.length) {
8224 name = null;
8225 newArgs = EMPTY_STRING_ARRAY;
8226 } else {
8227 name = args[opti];
8228 opti++;
8229 newArgs = new String[args.length - opti];
8230 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8231 args.length - opti);
8232 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008233 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008234 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008235 }
8236 return;
8237 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008238 String[] newArgs;
8239 String name;
8240 if (opti >= args.length) {
8241 name = null;
8242 newArgs = EMPTY_STRING_ARRAY;
8243 } else {
8244 name = args[opti];
8245 opti++;
8246 newArgs = new String[args.length - opti];
8247 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8248 args.length - opti);
8249 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008250 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008251 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008252 }
8253 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008254 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8255 synchronized (this) {
8256 dumpOomLocked(fd, pw, args, opti, true);
8257 }
8258 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008259 } else if ("provider".equals(cmd)) {
8260 String[] newArgs;
8261 String name;
8262 if (opti >= args.length) {
8263 name = null;
8264 newArgs = EMPTY_STRING_ARRAY;
8265 } else {
8266 name = args[opti];
8267 opti++;
8268 newArgs = new String[args.length - opti];
8269 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8270 }
8271 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8272 pw.println("No providers match: " + name);
8273 pw.println("Use -h for help.");
8274 }
8275 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008276 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8277 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008278 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008279 }
8280 return;
8281 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008282 String[] newArgs;
8283 String name;
8284 if (opti >= args.length) {
8285 name = null;
8286 newArgs = EMPTY_STRING_ARRAY;
8287 } else {
8288 name = args[opti];
8289 opti++;
8290 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008291 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8292 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008293 }
8294 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8295 pw.println("No services match: " + name);
8296 pw.println("Use -h for help.");
8297 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008298 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008299 } else if ("package".equals(cmd)) {
8300 String[] newArgs;
8301 if (opti >= args.length) {
8302 pw.println("package: no package name specified");
8303 pw.println("Use -h for help.");
8304 return;
8305 } else {
8306 dumpPackage = args[opti];
8307 opti++;
8308 newArgs = new String[args.length - opti];
8309 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8310 args.length - opti);
8311 args = newArgs;
8312 opti = 0;
8313 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008314 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8315 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008316 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008317 }
8318 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008319 } else {
8320 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008321 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8322 pw.println("Bad activity command, or no activities match: " + cmd);
8323 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008324 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008325 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008327 }
8328
8329 // No piece of data specified, dump everything.
8330 synchronized (this) {
8331 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008332 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008333 if (needSep) {
8334 pw.println(" ");
8335 }
8336 if (dumpAll) {
8337 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008338 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008339 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 if (needSep) {
8341 pw.println(" ");
8342 }
8343 if (dumpAll) {
8344 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008345 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008346 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008347 if (needSep) {
8348 pw.println(" ");
8349 }
8350 if (dumpAll) {
8351 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008352 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008353 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008354 if (needSep) {
8355 pw.println(" ");
8356 }
8357 if (dumpAll) {
8358 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008359 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008360 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008361 if (needSep) {
8362 pw.println(" ");
8363 }
8364 if (dumpAll) {
8365 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008366 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008367 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008368 }
8369 }
8370
8371 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008372 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008373 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8374 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008375 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8376 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008377 pw.println(" ");
8378 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008379 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8380 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008381 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008382 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008383 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008384 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008385 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008386 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008387 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008389 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008390 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008391 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008392 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008393 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8394 pw.println(" ");
8395 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008396 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008397 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008398 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008399 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008400 pw.println(" ");
8401 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008402 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008403 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008405
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008406 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008407 if (mMainStack.mPausingActivity != null) {
8408 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008410 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008411 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008412 if (dumpAll) {
8413 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8414 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008415 pw.println(" mDismissKeyguardOnNextActivity: "
8416 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008419 if (mRecentTasks.size() > 0) {
8420 pw.println();
8421 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008422
8423 final int N = mRecentTasks.size();
8424 for (int i=0; i<N; i++) {
8425 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008426 if (dumpPackage != null) {
8427 if (tr.realActivity == null ||
8428 !dumpPackage.equals(tr.realActivity)) {
8429 continue;
8430 }
8431 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008432 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8433 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008434 if (dumpAll) {
8435 mRecentTasks.get(i).dump(pw, " ");
8436 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008437 }
8438 }
8439
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008440 if (dumpAll) {
8441 pw.println(" ");
8442 pw.println(" mCurTask: " + mCurTask);
8443 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008444
8445 return true;
8446 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008447
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008448 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008449 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008450 boolean needSep = false;
8451 int numPers = 0;
8452
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008453 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8454
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008455 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8457 final int NA = procs.size();
8458 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008459 ProcessRecord r = procs.valueAt(ia);
8460 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8461 continue;
8462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008463 if (!needSep) {
8464 pw.println(" All known processes:");
8465 needSep = true;
8466 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008467 pw.print(r.persistent ? " *PERS*" : " *APP*");
8468 pw.print(" UID "); pw.print(procs.keyAt(ia));
8469 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470 r.dump(pw, " ");
8471 if (r.persistent) {
8472 numPers++;
8473 }
8474 }
8475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008476 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008477
8478 if (mIsolatedProcesses.size() > 0) {
8479 if (needSep) pw.println(" ");
8480 needSep = true;
8481 pw.println(" Isolated process list (sorted by uid):");
8482 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8483 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8484 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8485 continue;
8486 }
8487 pw.println(String.format("%sIsolated #%2d: %s",
8488 " ", i, r.toString()));
8489 }
8490 }
8491
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008492 if (mLruProcesses.size() > 0) {
8493 if (needSep) pw.println(" ");
8494 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008495 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008496 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008497 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008498 needSep = true;
8499 }
8500
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008501 if (dumpAll) {
8502 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008503 boolean printed = false;
8504 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8505 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8506 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8507 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008508 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008509 if (!printed) {
8510 if (needSep) pw.println(" ");
8511 needSep = true;
8512 pw.println(" PID mappings:");
8513 printed = true;
8514 }
8515 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8516 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 }
8518 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008519 }
8520
8521 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008522 synchronized (mPidsSelfLocked) {
8523 boolean printed = false;
8524 for (int i=0; i<mForegroundProcesses.size(); i++) {
8525 ProcessRecord r = mPidsSelfLocked.get(
8526 mForegroundProcesses.valueAt(i).pid);
8527 if (dumpPackage != null && (r == null
8528 || !dumpPackage.equals(r.info.packageName))) {
8529 continue;
8530 }
8531 if (!printed) {
8532 if (needSep) pw.println(" ");
8533 needSep = true;
8534 pw.println(" Foreground Processes:");
8535 printed = true;
8536 }
8537 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8538 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008540 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008541 }
8542
8543 if (mPersistentStartingProcesses.size() > 0) {
8544 if (needSep) pw.println(" ");
8545 needSep = true;
8546 pw.println(" Persisent processes that are starting:");
8547 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008548 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 if (mRemovedProcesses.size() > 0) {
8552 if (needSep) pw.println(" ");
8553 needSep = true;
8554 pw.println(" Processes that are being removed:");
8555 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008556 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008557 }
8558
8559 if (mProcessesOnHold.size() > 0) {
8560 if (needSep) pw.println(" ");
8561 needSep = true;
8562 pw.println(" Processes that are on old until the system is ready:");
8563 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008564 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008567 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568
8569 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008570 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008571 long now = SystemClock.uptimeMillis();
8572 for (Map.Entry<String, SparseArray<Long>> procs
8573 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008574 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008575 SparseArray<Long> uids = procs.getValue();
8576 final int N = uids.size();
8577 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008578 int puid = uids.keyAt(i);
8579 ProcessRecord r = mProcessNames.get(pname, puid);
8580 if (dumpPackage != null && (r == null
8581 || !dumpPackage.equals(r.info.packageName))) {
8582 continue;
8583 }
8584 if (!printed) {
8585 if (needSep) pw.println(" ");
8586 needSep = true;
8587 pw.println(" Time since processes crashed:");
8588 printed = true;
8589 }
8590 pw.print(" Process "); pw.print(pname);
8591 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008592 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008593 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8594 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008595 }
8596 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008601 for (Map.Entry<String, SparseArray<Long>> procs
8602 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008603 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008604 SparseArray<Long> uids = procs.getValue();
8605 final int N = uids.size();
8606 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008607 int puid = uids.keyAt(i);
8608 ProcessRecord r = mProcessNames.get(pname, puid);
8609 if (dumpPackage != null && (r == null
8610 || !dumpPackage.equals(r.info.packageName))) {
8611 continue;
8612 }
8613 if (!printed) {
8614 if (needSep) pw.println(" ");
8615 needSep = true;
8616 pw.println(" Bad processes:");
8617 }
8618 pw.print(" Bad process "); pw.print(pname);
8619 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008620 pw.print(": crashed at time ");
8621 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 }
8623 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008626 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008627 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008628 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008629 if (dumpAll) {
8630 StringBuilder sb = new StringBuilder(128);
8631 sb.append(" mPreviousProcessVisibleTime: ");
8632 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8633 pw.println(sb);
8634 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008635 if (mHeavyWeightProcess != null) {
8636 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8637 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008638 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008639 if (dumpAll) {
8640 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008641 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008642 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008643 for (Map.Entry<String, Integer> entry
8644 : mCompatModePackages.getPackages().entrySet()) {
8645 String pkg = entry.getKey();
8646 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008647 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8648 continue;
8649 }
8650 if (!printed) {
8651 pw.println(" mScreenCompatPackages:");
8652 printed = true;
8653 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008654 pw.print(" "); pw.print(pkg); pw.print(": ");
8655 pw.print(mode); pw.println();
8656 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008657 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008658 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8660 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8661 || mOrigWaitForDebugger) {
8662 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8663 + " mDebugTransient=" + mDebugTransient
8664 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8665 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008666 if (mOpenGlTraceApp != null) {
8667 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8668 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008669 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8670 || mProfileFd != null) {
8671 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8672 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8673 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8674 + mAutoStopProfiler);
8675 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008676 if (mAlwaysFinishActivities || mController != null) {
8677 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8678 + " mController=" + mController);
8679 }
8680 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008681 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008682 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008683 + " mProcessesReady=" + mProcessesReady
8684 + " mSystemReady=" + mSystemReady);
8685 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 + " mBooted=" + mBooted
8687 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008688 pw.print(" mLastPowerCheckRealtime=");
8689 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8690 pw.println("");
8691 pw.print(" mLastPowerCheckUptime=");
8692 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8693 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008694 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8695 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008696 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008697 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8698 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008700
8701 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008702 }
8703
Dianne Hackborn287952c2010-09-22 22:34:31 -07008704 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008705 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008706 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008707 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008708 long now = SystemClock.uptimeMillis();
8709 for (int i=0; i<mProcessesToGc.size(); i++) {
8710 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008711 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8712 continue;
8713 }
8714 if (!printed) {
8715 if (needSep) pw.println(" ");
8716 needSep = true;
8717 pw.println(" Processes that are waiting to GC:");
8718 printed = true;
8719 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008720 pw.print(" Process "); pw.println(proc);
8721 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8722 pw.print(", last gced=");
8723 pw.print(now-proc.lastRequestedGc);
8724 pw.print(" ms ago, last lowMem=");
8725 pw.print(now-proc.lastLowMemory);
8726 pw.println(" ms ago");
8727
8728 }
8729 }
8730 return needSep;
8731 }
8732
8733 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8734 int opti, boolean dumpAll) {
8735 boolean needSep = false;
8736
8737 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008738 if (needSep) pw.println(" ");
8739 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008740 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008741 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008742 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008743 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8744 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8745 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8746 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8747 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008748 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008749 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008750 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008751 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008752 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008753 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008754
8755 if (needSep) pw.println(" ");
8756 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008757 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008758 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008759 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008760 needSep = true;
8761 }
8762
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008763 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008764
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008765 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008766 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008767 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008768 if (mHeavyWeightProcess != null) {
8769 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8770 }
8771
8772 return true;
8773 }
8774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775 /**
8776 * There are three ways to call this:
8777 * - no service specified: dump all the services
8778 * - a flattened component name that matched an existing service was specified as the
8779 * first arg: dump that one service
8780 * - the first arg isn't the flattened component name of an existing service:
8781 * dump all services whose component contains the first arg as a substring
8782 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008783 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8784 int opti, boolean dumpAll) {
8785 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008787 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008788 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008789 try {
8790 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8791 for (UserInfo user : users) {
8792 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8793 services.add(r1);
8794 }
8795 }
8796 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008797 }
8798 }
8799 } else {
8800 ComponentName componentName = name != null
8801 ? ComponentName.unflattenFromString(name) : null;
8802 int objectId = 0;
8803 if (componentName == null) {
8804 // Not a '/' separated full component name; maybe an object ID?
8805 try {
8806 objectId = Integer.parseInt(name, 16);
8807 name = null;
8808 componentName = null;
8809 } catch (RuntimeException e) {
8810 }
8811 }
8812
8813 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008814 try {
8815 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8816 for (UserInfo user : users) {
8817 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8818 if (componentName != null) {
8819 if (r1.name.equals(componentName)) {
8820 services.add(r1);
8821 }
8822 } else if (name != null) {
8823 if (r1.name.flattenToString().contains(name)) {
8824 services.add(r1);
8825 }
8826 } else if (System.identityHashCode(r1) == objectId) {
8827 services.add(r1);
8828 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008829 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008830 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008831 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 }
8833 }
8834 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008835
8836 if (services.size() <= 0) {
8837 return false;
8838 }
8839
8840 boolean needSep = false;
8841 for (int i=0; i<services.size(); i++) {
8842 if (needSep) {
8843 pw.println();
8844 }
8845 needSep = true;
8846 dumpService("", fd, pw, services.get(i), args, dumpAll);
8847 }
8848 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 }
8850
8851 /**
8852 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8853 * there is a thread associated with the service.
8854 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008855 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8856 final ServiceRecord r, String[] args, boolean dumpAll) {
8857 String innerPrefix = prefix + " ";
8858 synchronized (this) {
8859 pw.print(prefix); pw.print("SERVICE ");
8860 pw.print(r.shortName); pw.print(" ");
8861 pw.print(Integer.toHexString(System.identityHashCode(r)));
8862 pw.print(" pid=");
8863 if (r.app != null) pw.println(r.app.pid);
8864 else pw.println("(not running)");
8865 if (dumpAll) {
8866 r.dump(pw, innerPrefix);
8867 }
8868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008870 pw.print(prefix); pw.println(" Client:");
8871 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008873 TransferPipe tp = new TransferPipe();
8874 try {
8875 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8876 tp.setBufferPrefix(prefix + " ");
8877 tp.go(fd);
8878 } finally {
8879 tp.kill();
8880 }
8881 } catch (IOException e) {
8882 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008884 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 }
8886 }
8887 }
8888
Marco Nelissen18cb2872011-11-15 11:19:53 -08008889 /**
8890 * There are three ways to call this:
8891 * - no provider specified: dump all the providers
8892 * - a flattened component name that matched an existing provider was specified as the
8893 * first arg: dump that one provider
8894 * - the first arg isn't the flattened component name of an existing provider:
8895 * dump all providers whose component contains the first arg as a substring
8896 */
8897 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8898 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008899 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008900 }
8901
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008902 static class ItemMatcher {
8903 ArrayList<ComponentName> components;
8904 ArrayList<String> strings;
8905 ArrayList<Integer> objects;
8906 boolean all;
8907
8908 ItemMatcher() {
8909 all = true;
8910 }
8911
8912 void build(String name) {
8913 ComponentName componentName = ComponentName.unflattenFromString(name);
8914 if (componentName != null) {
8915 if (components == null) {
8916 components = new ArrayList<ComponentName>();
8917 }
8918 components.add(componentName);
8919 all = false;
8920 } else {
8921 int objectId = 0;
8922 // Not a '/' separated full component name; maybe an object ID?
8923 try {
8924 objectId = Integer.parseInt(name, 16);
8925 if (objects == null) {
8926 objects = new ArrayList<Integer>();
8927 }
8928 objects.add(objectId);
8929 all = false;
8930 } catch (RuntimeException e) {
8931 // Not an integer; just do string match.
8932 if (strings == null) {
8933 strings = new ArrayList<String>();
8934 }
8935 strings.add(name);
8936 all = false;
8937 }
8938 }
8939 }
8940
8941 int build(String[] args, int opti) {
8942 for (; opti<args.length; opti++) {
8943 String name = args[opti];
8944 if ("--".equals(name)) {
8945 return opti+1;
8946 }
8947 build(name);
8948 }
8949 return opti;
8950 }
8951
8952 boolean match(Object object, ComponentName comp) {
8953 if (all) {
8954 return true;
8955 }
8956 if (components != null) {
8957 for (int i=0; i<components.size(); i++) {
8958 if (components.get(i).equals(comp)) {
8959 return true;
8960 }
8961 }
8962 }
8963 if (objects != null) {
8964 for (int i=0; i<objects.size(); i++) {
8965 if (System.identityHashCode(object) == objects.get(i)) {
8966 return true;
8967 }
8968 }
8969 }
8970 if (strings != null) {
8971 String flat = comp.flattenToString();
8972 for (int i=0; i<strings.size(); i++) {
8973 if (flat.contains(strings.get(i))) {
8974 return true;
8975 }
8976 }
8977 }
8978 return false;
8979 }
8980 }
8981
Dianne Hackborn625ac272010-09-17 18:29:22 -07008982 /**
8983 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008984 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008985 * - the cmd arg isn't the flattened component name of an existing activity:
8986 * dump all activity whose component contains the cmd as a substring
8987 * - A hex number of the ActivityRecord object instance.
8988 */
8989 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8990 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008991 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008992
8993 if ("all".equals(name)) {
8994 synchronized (this) {
8995 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008996 activities.add(r1);
8997 }
8998 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008999 } else if ("top".equals(name)) {
9000 synchronized (this) {
9001 final int N = mMainStack.mHistory.size();
9002 if (N > 0) {
9003 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9004 }
9005 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009006 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009007 ItemMatcher matcher = new ItemMatcher();
9008 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009009
9010 synchronized (this) {
9011 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009012 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009013 activities.add(r1);
9014 }
9015 }
9016 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009017 }
9018
9019 if (activities.size() <= 0) {
9020 return false;
9021 }
9022
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009023 String[] newArgs = new String[args.length - opti];
9024 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9025
Dianne Hackborn30d71892010-12-11 10:37:55 -08009026 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009027 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009028 for (int i=activities.size()-1; i>=0; i--) {
9029 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009030 if (needSep) {
9031 pw.println();
9032 }
9033 needSep = true;
9034 synchronized (this) {
9035 if (lastTask != r.task) {
9036 lastTask = r.task;
9037 pw.print("TASK "); pw.print(lastTask.affinity);
9038 pw.print(" id="); pw.println(lastTask.taskId);
9039 if (dumpAll) {
9040 lastTask.dump(pw, " ");
9041 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009042 }
9043 }
9044 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009045 }
9046 return true;
9047 }
9048
9049 /**
9050 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9051 * there is a thread associated with the activity.
9052 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009053 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009054 final ActivityRecord r, String[] args, boolean dumpAll) {
9055 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009056 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9058 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9059 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009060 if (r.app != null) pw.println(r.app.pid);
9061 else pw.println("(not running)");
9062 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009064 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009065 }
9066 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009067 // flush anything that is already in the PrintWriter since the thread is going
9068 // to write to the file descriptor directly
9069 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009070 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009071 TransferPipe tp = new TransferPipe();
9072 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009073 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9074 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009075 tp.go(fd);
9076 } finally {
9077 tp.kill();
9078 }
9079 } catch (IOException e) {
9080 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009081 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009082 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009083 }
9084 }
9085 }
9086
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009087 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009088 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009089 boolean needSep = false;
9090
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009091 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009092 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009094 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009095 Iterator it = mRegisteredReceivers.values().iterator();
9096 while (it.hasNext()) {
9097 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009098 if (dumpPackage != null && (r.app == null ||
9099 !dumpPackage.equals(r.app.info.packageName))) {
9100 continue;
9101 }
9102 if (!printed) {
9103 pw.println(" Registered Receivers:");
9104 needSep = true;
9105 printed = true;
9106 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009107 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 r.dump(pw, " ");
9109 }
9110 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009111
9112 if (mReceiverResolver.dump(pw, needSep ?
9113 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9114 " ", dumpPackage, false)) {
9115 needSep = true;
9116 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009117 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009118
9119 for (BroadcastQueue q : mBroadcastQueues) {
9120 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009123 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009124
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009125 if (mStickyBroadcasts != null && dumpPackage == null) {
9126 if (needSep) {
9127 pw.println();
9128 }
9129 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009130 pw.println(" Sticky broadcasts:");
9131 StringBuilder sb = new StringBuilder(128);
9132 for (Map.Entry<String, ArrayList<Intent>> ent
9133 : mStickyBroadcasts.entrySet()) {
9134 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009135 if (dumpAll) {
9136 pw.println(":");
9137 ArrayList<Intent> intents = ent.getValue();
9138 final int N = intents.size();
9139 for (int i=0; i<N; i++) {
9140 sb.setLength(0);
9141 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009142 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009143 pw.println(sb.toString());
9144 Bundle bundle = intents.get(i).getExtras();
9145 if (bundle != null) {
9146 pw.print(" ");
9147 pw.println(bundle.toString());
9148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009150 } else {
9151 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009152 }
9153 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009154 needSep = true;
9155 }
9156
9157 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009158 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009159 for (BroadcastQueue queue : mBroadcastQueues) {
9160 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9161 + queue.mBroadcastsScheduled);
9162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009163 pw.println(" mHandler:");
9164 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009165 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009167
9168 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 }
9170
Marco Nelissen18cb2872011-11-15 11:19:53 -08009171 /**
9172 * Prints a list of ServiceRecords (dumpsys activity services)
9173 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009174 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009175 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009176 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009178 ItemMatcher matcher = new ItemMatcher();
9179 matcher.build(args, opti);
9180
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009181 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009182 try {
9183 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9184 for (UserInfo user : users) {
9185 if (mServiceMap.getAllServices(user.id).size() > 0) {
9186 boolean printed = false;
9187 long nowReal = SystemClock.elapsedRealtime();
9188 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9189 user.id).iterator();
9190 needSep = false;
9191 while (it.hasNext()) {
9192 ServiceRecord r = it.next();
9193 if (!matcher.match(r, r.name)) {
9194 continue;
9195 }
9196 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9197 continue;
9198 }
9199 if (!printed) {
9200 pw.println(" Active services:");
9201 printed = true;
9202 }
9203 if (needSep) {
9204 pw.println();
9205 }
9206 pw.print(" * ");
9207 pw.println(r);
9208 if (dumpAll) {
9209 r.dump(pw, " ");
9210 needSep = true;
9211 } else {
9212 pw.print(" app=");
9213 pw.println(r.app);
9214 pw.print(" created=");
9215 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9216 pw.print(" started=");
9217 pw.print(r.startRequested);
9218 pw.print(" connections=");
9219 pw.println(r.connections.size());
9220 if (r.connections.size() > 0) {
9221 pw.println(" Connections:");
9222 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9223 for (int i = 0; i < clist.size(); i++) {
9224 ConnectionRecord conn = clist.get(i);
9225 pw.print(" ");
9226 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009227 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009228 pw.print(" -> ");
9229 ProcessRecord proc = conn.binding.client;
9230 pw.println(proc != null ? proc.toShortString() : "null");
9231 }
9232 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009233 }
9234 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009235 if (dumpClient && r.app != null && r.app.thread != null) {
9236 pw.println(" Client:");
9237 pw.flush();
9238 try {
9239 TransferPipe tp = new TransferPipe();
9240 try {
9241 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9242 r, args);
9243 tp.setBufferPrefix(" ");
9244 // Short timeout, since blocking here can
9245 // deadlock with the application.
9246 tp.go(fd, 2000);
9247 } finally {
9248 tp.kill();
9249 }
9250 } catch (IOException e) {
9251 pw.println(" Failure while dumping the service: " + e);
9252 } catch (RemoteException e) {
9253 pw.println(" Got a RemoteException while dumping the service");
9254 }
9255 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009256 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009257 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009258 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009260 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009261 } catch (RemoteException re) {
9262
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009264
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009266 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009267 for (int i=0; i<mPendingServices.size(); i++) {
9268 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009269 if (!matcher.match(r, r.name)) {
9270 continue;
9271 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009272 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9273 continue;
9274 }
9275 if (!printed) {
9276 if (needSep) pw.println(" ");
9277 needSep = true;
9278 pw.println(" Pending services:");
9279 printed = true;
9280 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 pw.print(" * Pending "); pw.println(r);
9282 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009284 needSep = true;
9285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009287 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009288 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009289 for (int i=0; i<mRestartingServices.size(); i++) {
9290 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009291 if (!matcher.match(r, r.name)) {
9292 continue;
9293 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009294 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9295 continue;
9296 }
9297 if (!printed) {
9298 if (needSep) pw.println(" ");
9299 needSep = true;
9300 pw.println(" Restarting services:");
9301 printed = true;
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 pw.print(" * Restarting "); pw.println(r);
9304 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009306 needSep = true;
9307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 for (int i=0; i<mStoppingServices.size(); i++) {
9312 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009313 if (!matcher.match(r, r.name)) {
9314 continue;
9315 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009316 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9317 continue;
9318 }
9319 if (!printed) {
9320 if (needSep) pw.println(" ");
9321 needSep = true;
9322 pw.println(" Stopping services:");
9323 printed = true;
9324 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009325 pw.print(" * Stopping "); pw.println(r);
9326 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009328 needSep = true;
9329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009331 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009333 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009334 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 = mServiceConnections.values().iterator();
9336 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009337 ArrayList<ConnectionRecord> r = it.next();
9338 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009339 ConnectionRecord cr = r.get(i);
9340 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9341 continue;
9342 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009343 if (dumpPackage != null && (cr.binding.client == null
9344 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9345 continue;
9346 }
9347 if (!printed) {
9348 if (needSep) pw.println(" ");
9349 needSep = true;
9350 pw.println(" Connection bindings to services:");
9351 printed = true;
9352 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009353 pw.print(" * "); pw.println(cr);
9354 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 }
9359 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009360
9361 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 }
9363
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009364 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009365 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009366 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009368 ItemMatcher matcher = new ItemMatcher();
9369 matcher.build(args, opti);
9370
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009371 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009372
9373 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009374
9375 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009378 ContentProviderRecord r = mLaunchingProviders.get(i);
9379 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9380 continue;
9381 }
9382 if (!printed) {
9383 if (needSep) pw.println(" ");
9384 needSep = true;
9385 pw.println(" Launching content providers:");
9386 printed = true;
9387 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009389 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009390 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009391 }
9392
9393 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009394 if (needSep) pw.println();
9395 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009396 pw.println("Granted Uri Permissions:");
9397 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9398 int uid = mGrantedUriPermissions.keyAt(i);
9399 HashMap<Uri, UriPermission> perms
9400 = mGrantedUriPermissions.valueAt(i);
9401 pw.print(" * UID "); pw.print(uid);
9402 pw.println(" holds:");
9403 for (UriPermission perm : perms.values()) {
9404 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009405 if (dumpAll) {
9406 perm.dump(pw, " ");
9407 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009408 }
9409 }
9410 needSep = true;
9411 }
9412
9413 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 }
9415
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009417 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009418 boolean needSep = false;
9419
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009420 if (mIntentSenderRecords.size() > 0) {
9421 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009422 Iterator<WeakReference<PendingIntentRecord>> it
9423 = mIntentSenderRecords.values().iterator();
9424 while (it.hasNext()) {
9425 WeakReference<PendingIntentRecord> ref = it.next();
9426 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009427 if (dumpPackage != null && (rec == null
9428 || !dumpPackage.equals(rec.key.packageName))) {
9429 continue;
9430 }
9431 if (!printed) {
9432 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9433 printed = true;
9434 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009435 needSep = true;
9436 if (rec != null) {
9437 pw.print(" * "); pw.println(rec);
9438 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009439 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009440 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009441 } else {
9442 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443 }
9444 }
9445 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009446
9447 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 }
9449
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009450 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009451 String prefix, String label, boolean complete, boolean brief, boolean client,
9452 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009454 boolean needNL = false;
9455 final String innerPrefix = prefix + " ";
9456 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009457 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009458 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009459 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9460 continue;
9461 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009462 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 if (needNL) {
9464 pw.println(" ");
9465 needNL = false;
9466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 if (lastTask != r.task) {
9468 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009469 pw.print(prefix);
9470 pw.print(full ? "* " : " ");
9471 pw.println(lastTask);
9472 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009473 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009474 } else if (complete) {
9475 // Complete + brief == give a summary. Isn't that obvious?!?
9476 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009477 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009478 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009479 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009481 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009482 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9483 pw.print(" #"); pw.print(i); pw.print(": ");
9484 pw.println(r);
9485 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009486 r.dump(pw, innerPrefix);
9487 } else if (complete) {
9488 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009489 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009490 if (r.app != null) {
9491 pw.print(innerPrefix); pw.println(r.app);
9492 }
9493 }
9494 if (client && r.app != null && r.app.thread != null) {
9495 // flush anything that is already in the PrintWriter since the thread is going
9496 // to write to the file descriptor directly
9497 pw.flush();
9498 try {
9499 TransferPipe tp = new TransferPipe();
9500 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009501 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9502 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009503 // Short timeout, since blocking here can
9504 // deadlock with the application.
9505 tp.go(fd, 2000);
9506 } finally {
9507 tp.kill();
9508 }
9509 } catch (IOException e) {
9510 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9511 } catch (RemoteException e) {
9512 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9513 }
9514 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516 }
9517 }
9518
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009519 private static String buildOomTag(String prefix, String space, int val, int base) {
9520 if (val == base) {
9521 if (space == null) return prefix;
9522 return prefix + " ";
9523 }
9524 return prefix + "+" + Integer.toString(val-base);
9525 }
9526
9527 private static final int dumpProcessList(PrintWriter pw,
9528 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009529 String prefix, String normalLabel, String persistentLabel,
9530 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009532 final int N = list.size()-1;
9533 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009534 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009535 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9536 continue;
9537 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009538 pw.println(String.format("%s%s #%2d: %s",
9539 prefix, (r.persistent ? persistentLabel : normalLabel),
9540 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009541 if (r.persistent) {
9542 numPers++;
9543 }
9544 }
9545 return numPers;
9546 }
9547
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009548 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009549 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009550 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009551 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009552
Dianne Hackborn905577f2011-09-07 18:31:28 -07009553 ArrayList<Pair<ProcessRecord, Integer>> list
9554 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9555 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009556 ProcessRecord r = origList.get(i);
9557 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9558 continue;
9559 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009560 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9561 }
9562
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009563 if (list.size() <= 0) {
9564 return false;
9565 }
9566
Dianne Hackborn905577f2011-09-07 18:31:28 -07009567 Comparator<Pair<ProcessRecord, Integer>> comparator
9568 = new Comparator<Pair<ProcessRecord, Integer>>() {
9569 @Override
9570 public int compare(Pair<ProcessRecord, Integer> object1,
9571 Pair<ProcessRecord, Integer> object2) {
9572 if (object1.first.setAdj != object2.first.setAdj) {
9573 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9574 }
9575 if (object1.second.intValue() != object2.second.intValue()) {
9576 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9577 }
9578 return 0;
9579 }
9580 };
9581
9582 Collections.sort(list, comparator);
9583
Dianne Hackborn287952c2010-09-22 22:34:31 -07009584 final long curRealtime = SystemClock.elapsedRealtime();
9585 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9586 final long curUptime = SystemClock.uptimeMillis();
9587 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9588
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009589 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009590 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009591 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009592 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009593 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009594 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9595 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009596 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9597 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009598 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9599 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009600 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9601 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009602 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009603 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009604 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9605 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9606 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9607 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9608 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9609 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9610 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9611 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009612 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9613 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009614 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9615 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009616 } else {
9617 oomAdj = Integer.toString(r.setAdj);
9618 }
9619 String schedGroup;
9620 switch (r.setSchedGroup) {
9621 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9622 schedGroup = "B";
9623 break;
9624 case Process.THREAD_GROUP_DEFAULT:
9625 schedGroup = "F";
9626 break;
9627 default:
9628 schedGroup = Integer.toString(r.setSchedGroup);
9629 break;
9630 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009631 String foreground;
9632 if (r.foregroundActivities) {
9633 foreground = "A";
9634 } else if (r.foregroundServices) {
9635 foreground = "S";
9636 } else {
9637 foreground = " ";
9638 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009639 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009640 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009641 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9642 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009643 if (r.adjSource != null || r.adjTarget != null) {
9644 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009645 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009646 if (r.adjTarget instanceof ComponentName) {
9647 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9648 } else if (r.adjTarget != null) {
9649 pw.print(r.adjTarget.toString());
9650 } else {
9651 pw.print("{null}");
9652 }
9653 pw.print("<=");
9654 if (r.adjSource instanceof ProcessRecord) {
9655 pw.print("Proc{");
9656 pw.print(((ProcessRecord)r.adjSource).toShortString());
9657 pw.println("}");
9658 } else if (r.adjSource != null) {
9659 pw.println(r.adjSource.toString());
9660 } else {
9661 pw.println("{null}");
9662 }
9663 }
9664 if (inclDetails) {
9665 pw.print(prefix);
9666 pw.print(" ");
9667 pw.print("oom: max="); pw.print(r.maxAdj);
9668 pw.print(" hidden="); pw.print(r.hiddenAdj);
9669 pw.print(" curRaw="); pw.print(r.curRawAdj);
9670 pw.print(" setRaw="); pw.print(r.setRawAdj);
9671 pw.print(" cur="); pw.print(r.curAdj);
9672 pw.print(" set="); pw.println(r.setAdj);
9673 pw.print(prefix);
9674 pw.print(" ");
9675 pw.print("keeping="); pw.print(r.keeping);
9676 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009677 pw.print(" empty="); pw.print(r.empty);
9678 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009679
9680 if (!r.keeping) {
9681 if (r.lastWakeTime != 0) {
9682 long wtime;
9683 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9684 synchronized (stats) {
9685 wtime = stats.getProcessWakeTime(r.info.uid,
9686 r.pid, curRealtime);
9687 }
9688 long timeUsed = wtime - r.lastWakeTime;
9689 pw.print(prefix);
9690 pw.print(" ");
9691 pw.print("keep awake over ");
9692 TimeUtils.formatDuration(realtimeSince, pw);
9693 pw.print(" used ");
9694 TimeUtils.formatDuration(timeUsed, pw);
9695 pw.print(" (");
9696 pw.print((timeUsed*100)/realtimeSince);
9697 pw.println("%)");
9698 }
9699 if (r.lastCpuTime != 0) {
9700 long timeUsed = r.curCpuTime - r.lastCpuTime;
9701 pw.print(prefix);
9702 pw.print(" ");
9703 pw.print("run cpu over ");
9704 TimeUtils.formatDuration(uptimeSince, pw);
9705 pw.print(" used ");
9706 TimeUtils.formatDuration(timeUsed, pw);
9707 pw.print(" (");
9708 pw.print((timeUsed*100)/uptimeSince);
9709 pw.println("%)");
9710 }
9711 }
9712 }
9713 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009714 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009715 }
9716
Dianne Hackbornb437e092011-08-05 17:50:29 -07009717 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009718 ArrayList<ProcessRecord> procs;
9719 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009720 if (args != null && args.length > start
9721 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009722 procs = new ArrayList<ProcessRecord>();
9723 int pid = -1;
9724 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009725 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009726 } catch (NumberFormatException e) {
9727
9728 }
9729 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9730 ProcessRecord proc = mLruProcesses.get(i);
9731 if (proc.pid == pid) {
9732 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009733 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009734 procs.add(proc);
9735 }
9736 }
9737 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009738 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009739 return null;
9740 }
9741 } else {
9742 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9743 }
9744 }
9745 return procs;
9746 }
9747
9748 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9749 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009750 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009751 if (procs == null) {
9752 return;
9753 }
9754
9755 long uptime = SystemClock.uptimeMillis();
9756 long realtime = SystemClock.elapsedRealtime();
9757 pw.println("Applications Graphics Acceleration Info:");
9758 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9759
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009760 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9761 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009762 if (r.thread != null) {
9763 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9764 pw.flush();
9765 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009766 TransferPipe tp = new TransferPipe();
9767 try {
9768 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9769 tp.go(fd);
9770 } finally {
9771 tp.kill();
9772 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009773 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009774 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009775 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009776 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009777 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009778 pw.flush();
9779 }
9780 }
9781 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009782 }
9783
Jeff Brown6754ba22011-12-14 20:20:01 -08009784 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9785 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9786 if (procs == null) {
9787 return;
9788 }
9789
9790 pw.println("Applications Database Info:");
9791
9792 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9793 ProcessRecord r = procs.get(i);
9794 if (r.thread != null) {
9795 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9796 pw.flush();
9797 try {
9798 TransferPipe tp = new TransferPipe();
9799 try {
9800 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9801 tp.go(fd);
9802 } finally {
9803 tp.kill();
9804 }
9805 } catch (IOException e) {
9806 pw.println("Failure while dumping the app: " + r);
9807 pw.flush();
9808 } catch (RemoteException e) {
9809 pw.println("Got a RemoteException while dumping the app " + r);
9810 pw.flush();
9811 }
9812 }
9813 }
9814 }
9815
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009816 final static class MemItem {
9817 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009818 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009819 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009820 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009821 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009822
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009823 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009824 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009825 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009826 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009827 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009828 }
9829 }
9830
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009831 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009832 boolean sort) {
9833 if (sort) {
9834 Collections.sort(items, new Comparator<MemItem>() {
9835 @Override
9836 public int compare(MemItem lhs, MemItem rhs) {
9837 if (lhs.pss < rhs.pss) {
9838 return 1;
9839 } else if (lhs.pss > rhs.pss) {
9840 return -1;
9841 }
9842 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009843 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009844 });
9845 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009846
9847 for (int i=0; i<items.size(); i++) {
9848 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009849 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009850 if (mi.subitems != null) {
9851 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9852 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009853 }
9854 }
9855
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009856 // These are in KB.
9857 static final long[] DUMP_MEM_BUCKETS = new long[] {
9858 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9859 120*1024, 160*1024, 200*1024,
9860 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9861 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9862 };
9863
Dianne Hackborn672342c2011-11-29 11:29:02 -08009864 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9865 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009866 int start = label.lastIndexOf('.');
9867 if (start >= 0) start++;
9868 else start = 0;
9869 int end = label.length();
9870 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9871 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9872 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9873 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009874 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009875 out.append(label, start, end);
9876 return;
9877 }
9878 }
9879 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009880 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009881 out.append(label, start, end);
9882 }
9883
9884 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9885 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9886 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9887 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9888 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9889 };
9890 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9891 "System", "Persistent", "Foreground",
9892 "Visible", "Perceptible", "Heavy Weight",
9893 "Backup", "A Services", "Home", "Previous",
9894 "B Services", "Background"
9895 };
9896
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009897 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009898 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009899 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009900 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009901 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009902
9903 int opti = 0;
9904 while (opti < args.length) {
9905 String opt = args[opti];
9906 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9907 break;
9908 }
9909 opti++;
9910 if ("-a".equals(opt)) {
9911 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009912 } else if ("--oom".equals(opt)) {
9913 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009914 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009915 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009916 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009917 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009918 pw.println("If [process] is specified it can be the name or ");
9919 pw.println("pid of a specific process to dump.");
9920 return;
9921 } else {
9922 pw.println("Unknown argument: " + opt + "; use -h for help");
9923 }
9924 }
9925
9926 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009927 if (procs == null) {
9928 return;
9929 }
9930
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009931 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009932 long uptime = SystemClock.uptimeMillis();
9933 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009934
9935 if (procs.size() == 1 || isCheckinRequest) {
9936 dumpAll = true;
9937 }
9938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009939 if (isCheckinRequest) {
9940 // short checkin version
9941 pw.println(uptime + "," + realtime);
9942 pw.flush();
9943 } else {
9944 pw.println("Applications Memory Usage (kB):");
9945 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9946 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009947
Dianne Hackbornb437e092011-08-05 17:50:29 -07009948 String[] innerArgs = new String[args.length-opti];
9949 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9950
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009951 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9952 long nativePss=0, dalvikPss=0, otherPss=0;
9953 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9954
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009955 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9956 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9957 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009958
9959 long totalPss = 0;
9960
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009961 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9962 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009963 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009964 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009965 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9966 pw.flush();
9967 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009968 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009969 if (dumpAll) {
9970 try {
9971 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9972 } catch (RemoteException e) {
9973 if (!isCheckinRequest) {
9974 pw.println("Got RemoteException!");
9975 pw.flush();
9976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009977 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009978 } else {
9979 mi = new Debug.MemoryInfo();
9980 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009981 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009982
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009983 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009984 long myTotalPss = mi.getTotalPss();
9985 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009986 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009987 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009988 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009989
9990 nativePss += mi.nativePss;
9991 dalvikPss += mi.dalvikPss;
9992 otherPss += mi.otherPss;
9993 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9994 long mem = mi.getOtherPss(j);
9995 miscPss[j] += mem;
9996 otherPss -= mem;
9997 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009998
9999 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010000 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10001 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010002 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010003 if (oomProcs[oomIndex] == null) {
10004 oomProcs[oomIndex] = new ArrayList<MemItem>();
10005 }
10006 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010007 break;
10008 }
10009 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010011 }
10012 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010013
10014 if (!isCheckinRequest && procs.size() > 1) {
10015 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10016
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010017 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10018 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10019 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010020 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010021 String label = Debug.MemoryInfo.getOtherLabel(j);
10022 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010023 }
10024
Dianne Hackbornb437e092011-08-05 17:50:29 -070010025 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10026 for (int j=0; j<oomPss.length; j++) {
10027 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010028 String label = DUMP_MEM_OOM_LABEL[j];
10029 MemItem item = new MemItem(label, label, oomPss[j],
10030 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010031 item.subitems = oomProcs[j];
10032 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010033 }
10034 }
10035
Dianne Hackborn672342c2011-11-29 11:29:02 -080010036 if (outTag != null || outStack != null) {
10037 if (outTag != null) {
10038 appendMemBucket(outTag, totalPss, "total", false);
10039 }
10040 if (outStack != null) {
10041 appendMemBucket(outStack, totalPss, "total", true);
10042 }
10043 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010044 for (int i=0; i<oomMems.size(); i++) {
10045 MemItem miCat = oomMems.get(i);
10046 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10047 continue;
10048 }
10049 if (miCat.id < ProcessList.SERVICE_ADJ
10050 || miCat.id == ProcessList.HOME_APP_ADJ
10051 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010052 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10053 outTag.append(" / ");
10054 }
10055 if (outStack != null) {
10056 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10057 if (firstLine) {
10058 outStack.append(":");
10059 firstLine = false;
10060 }
10061 outStack.append("\n\t at ");
10062 } else {
10063 outStack.append("$");
10064 }
10065 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010066 for (int j=0; j<miCat.subitems.size(); j++) {
10067 MemItem mi = miCat.subitems.get(j);
10068 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010069 if (outTag != null) {
10070 outTag.append(" ");
10071 }
10072 if (outStack != null) {
10073 outStack.append("$");
10074 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010075 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010076 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10077 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10078 }
10079 if (outStack != null) {
10080 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10081 }
10082 }
10083 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10084 outStack.append("(");
10085 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10086 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10087 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10088 outStack.append(":");
10089 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10090 }
10091 }
10092 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010093 }
10094 }
10095 }
10096 }
10097
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010098 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010099 pw.println();
10100 pw.println("Total PSS by process:");
10101 dumpMemItems(pw, " ", procMems, true);
10102 pw.println();
10103 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010104 pw.println("Total PSS by OOM adjustment:");
10105 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010106 if (!oomOnly) {
10107 PrintWriter out = categoryPw != null ? categoryPw : pw;
10108 out.println();
10109 out.println("Total PSS by category:");
10110 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010111 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010112 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010113 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010115 }
10116
10117 /**
10118 * Searches array of arguments for the specified string
10119 * @param args array of argument strings
10120 * @param value value to search for
10121 * @return true if the value is contained in the array
10122 */
10123 private static boolean scanArgs(String[] args, String value) {
10124 if (args != null) {
10125 for (String arg : args) {
10126 if (value.equals(arg)) {
10127 return true;
10128 }
10129 }
10130 }
10131 return false;
10132 }
10133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010134 private final void killServicesLocked(ProcessRecord app,
10135 boolean allowRestart) {
10136 // Report disconnected services.
10137 if (false) {
10138 // XXX we are letting the client link to the service for
10139 // death notifications.
10140 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010141 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010142 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010143 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010144 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010145 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010146 = r.connections.values().iterator();
10147 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010148 ArrayList<ConnectionRecord> cl = jt.next();
10149 for (int i=0; i<cl.size(); i++) {
10150 ConnectionRecord c = cl.get(i);
10151 if (c.binding.client != app) {
10152 try {
10153 //c.conn.connected(r.className, null);
10154 } catch (Exception e) {
10155 // todo: this should be asynchronous!
10156 Slog.w(TAG, "Exception thrown disconnected servce "
10157 + r.shortName
10158 + " from app " + app.processName, e);
10159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010160 }
10161 }
10162 }
10163 }
10164 }
10165 }
10166 }
10167
10168 // Clean up any connections this application has to other services.
10169 if (app.connections.size() > 0) {
10170 Iterator<ConnectionRecord> it = app.connections.iterator();
10171 while (it.hasNext()) {
10172 ConnectionRecord r = it.next();
10173 removeConnectionLocked(r, app, null);
10174 }
10175 }
10176 app.connections.clear();
10177
10178 if (app.services.size() != 0) {
10179 // Any services running in the application need to be placed
10180 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010181 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010182 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010183 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010184 synchronized (sr.stats.getBatteryStats()) {
10185 sr.stats.stopLaunchedLocked();
10186 }
10187 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010188 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010189 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010190 if (mStoppingServices.remove(sr)) {
10191 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10192 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010193
10194 boolean hasClients = sr.bindings.size() > 0;
10195 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010196 Iterator<IntentBindRecord> bindings
10197 = sr.bindings.values().iterator();
10198 while (bindings.hasNext()) {
10199 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010200 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010201 + ": shouldUnbind=" + b.hasBound);
10202 b.binder = null;
10203 b.requested = b.received = b.hasBound = false;
10204 }
10205 }
10206
Dianne Hackborn070783f2010-12-29 16:46:28 -080010207 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10208 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010209 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010211 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010212 sr.crashCount, sr.shortName, app.pid);
10213 bringDownServiceLocked(sr, true);
10214 } else if (!allowRestart) {
10215 bringDownServiceLocked(sr, true);
10216 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010217 boolean canceled = scheduleServiceRestartLocked(sr, true);
10218
10219 // Should the service remain running? Note that in the
10220 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010221 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010222 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10223 if (sr.pendingStarts.size() == 0) {
10224 sr.startRequested = false;
10225 if (!hasClients) {
10226 // Whoops, no reason to restart!
10227 bringDownServiceLocked(sr, true);
10228 }
10229 }
10230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010231 }
10232 }
10233
10234 if (!allowRestart) {
10235 app.services.clear();
10236 }
10237 }
10238
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010239 // Make sure we have no more records on the stopping list.
10240 int i = mStoppingServices.size();
10241 while (i > 0) {
10242 i--;
10243 ServiceRecord sr = mStoppingServices.get(i);
10244 if (sr.app == app) {
10245 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010246 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010247 }
10248 }
10249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010250 app.executingServices.clear();
10251 }
10252
10253 private final void removeDyingProviderLocked(ProcessRecord proc,
10254 ContentProviderRecord cpr) {
10255 synchronized (cpr) {
10256 cpr.launchingApp = null;
10257 cpr.notifyAll();
10258 }
10259
Amith Yamasani742a6712011-05-04 14:49:28 -070010260 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 String names[] = cpr.info.authority.split(";");
10262 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010263 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010264 }
10265
10266 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10267 while (cit.hasNext()) {
10268 ProcessRecord capp = cit.next();
10269 if (!capp.persistent && capp.thread != null
10270 && capp.pid != 0
10271 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010272 Slog.i(TAG, "Kill " + capp.processName
10273 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010274 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010275 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010276 capp.processName, capp.setAdj, "dying provider "
10277 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010278 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010279 }
10280 }
10281
10282 mLaunchingProviders.remove(cpr);
10283 }
10284
10285 /**
10286 * Main code for cleaning up a process when it has gone away. This is
10287 * called both as a result of the process dying, or directly when stopping
10288 * a process when running in single process mode.
10289 */
10290 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010291 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010292 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010293 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010294 }
10295
Dianne Hackborn36124872009-10-08 16:22:03 -070010296 mProcessesToGc.remove(app);
10297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010298 // Dismiss any open dialogs.
10299 if (app.crashDialog != null) {
10300 app.crashDialog.dismiss();
10301 app.crashDialog = null;
10302 }
10303 if (app.anrDialog != null) {
10304 app.anrDialog.dismiss();
10305 app.anrDialog = null;
10306 }
10307 if (app.waitDialog != null) {
10308 app.waitDialog.dismiss();
10309 app.waitDialog = null;
10310 }
10311
10312 app.crashing = false;
10313 app.notResponding = false;
10314
10315 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010316 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010317 app.thread = null;
10318 app.forcingToForeground = null;
10319 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010320 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010321 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010322 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010323
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010324 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010325
10326 boolean restart = false;
10327
10328 int NL = mLaunchingProviders.size();
10329
10330 // Remove published content providers.
10331 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010332 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010334 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010335 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010336 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010337
10338 // See if someone is waiting for this provider... in which
10339 // case we don't remove it, but just let it restart.
10340 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010341 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 for (; i<NL; i++) {
10343 if (mLaunchingProviders.get(i) == cpr) {
10344 restart = true;
10345 break;
10346 }
10347 }
10348 } else {
10349 i = NL;
10350 }
10351
10352 if (i >= NL) {
10353 removeDyingProviderLocked(app, cpr);
10354 NL = mLaunchingProviders.size();
10355 }
10356 }
10357 app.pubProviders.clear();
10358 }
10359
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010360 // Take care of any launching providers waiting for this process.
10361 if (checkAppInLaunchingProvidersLocked(app, false)) {
10362 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010365 // Unregister from connected content providers.
10366 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010367 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010368 while (it.hasNext()) {
10369 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10370 cpr.clients.remove(app);
10371 }
10372 app.conProviders.clear();
10373 }
10374
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010375 // At this point there may be remaining entries in mLaunchingProviders
10376 // where we were the only one waiting, so they are no longer of use.
10377 // Look for these and clean up if found.
10378 // XXX Commented out for now. Trying to figure out a way to reproduce
10379 // the actual situation to identify what is actually going on.
10380 if (false) {
10381 for (int i=0; i<NL; i++) {
10382 ContentProviderRecord cpr = (ContentProviderRecord)
10383 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010384 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010385 synchronized (cpr) {
10386 cpr.launchingApp = null;
10387 cpr.notifyAll();
10388 }
10389 }
10390 }
10391 }
10392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010393 skipCurrentReceiverLocked(app);
10394
10395 // Unregister any receivers.
10396 if (app.receivers.size() > 0) {
10397 Iterator<ReceiverList> it = app.receivers.iterator();
10398 while (it.hasNext()) {
10399 removeReceiverLocked(it.next());
10400 }
10401 app.receivers.clear();
10402 }
10403
Christopher Tate181fafa2009-05-14 11:12:14 -070010404 // If the app is undergoing backup, tell the backup manager about it
10405 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010406 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010407 try {
10408 IBackupManager bm = IBackupManager.Stub.asInterface(
10409 ServiceManager.getService(Context.BACKUP_SERVICE));
10410 bm.agentDisconnected(app.info.packageName);
10411 } catch (RemoteException e) {
10412 // can't happen; backup manager is local
10413 }
10414 }
10415
Jeff Sharkey287bd832011-05-28 19:36:26 -070010416 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010418 // If the caller is restarting this app, then leave it in its
10419 // current lists and let the caller take care of it.
10420 if (restarting) {
10421 return;
10422 }
10423
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010424 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010425 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010426 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010427 mProcessNames.remove(app.processName, app.uid);
10428 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010429 if (mHeavyWeightProcess == app) {
10430 mHeavyWeightProcess = null;
10431 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010433 } else if (!app.removed) {
10434 // This app is persistent, so we need to keep its record around.
10435 // If it is not already on the pending app list, add it there
10436 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010437 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10438 mPersistentStartingProcesses.add(app);
10439 restart = true;
10440 }
10441 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010442 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10443 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010444 mProcessesOnHold.remove(app);
10445
The Android Open Source Project4df24232009-03-05 14:34:35 -080010446 if (app == mHomeProcess) {
10447 mHomeProcess = null;
10448 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010449 if (app == mPreviousProcess) {
10450 mPreviousProcess = null;
10451 }
10452
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010453 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010454 // We have components that still need to be running in the
10455 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010456 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457 startProcessLocked(app, "restart", app.processName);
10458 } else if (app.pid > 0 && app.pid != MY_PID) {
10459 // Goodbye!
10460 synchronized (mPidsSelfLocked) {
10461 mPidsSelfLocked.remove(app.pid);
10462 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10463 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010464 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010465 }
10466 }
10467
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010468 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10469 // Look through the content providers we are waiting to have launched,
10470 // and if any run in this process then either schedule a restart of
10471 // the process or kill the client waiting for it if this process has
10472 // gone bad.
10473 int NL = mLaunchingProviders.size();
10474 boolean restart = false;
10475 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010476 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010477 if (cpr.launchingApp == app) {
10478 if (!alwaysBad && !app.bad) {
10479 restart = true;
10480 } else {
10481 removeDyingProviderLocked(app, cpr);
10482 NL = mLaunchingProviders.size();
10483 }
10484 }
10485 }
10486 return restart;
10487 }
10488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010489 // =========================================================
10490 // SERVICES
10491 // =========================================================
10492
10493 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10494 ActivityManager.RunningServiceInfo info =
10495 new ActivityManager.RunningServiceInfo();
10496 info.service = r.name;
10497 if (r.app != null) {
10498 info.pid = r.app.pid;
10499 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010500 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010501 info.process = r.processName;
10502 info.foreground = r.isForeground;
10503 info.activeSince = r.createTime;
10504 info.started = r.startRequested;
10505 info.clientCount = r.connections.size();
10506 info.crashCount = r.crashCount;
10507 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010508 if (r.isForeground) {
10509 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10510 }
10511 if (r.startRequested) {
10512 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10513 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010514 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010515 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10516 }
10517 if (r.app != null && r.app.persistent) {
10518 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10519 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010520
10521 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10522 for (int i=0; i<connl.size(); i++) {
10523 ConnectionRecord conn = connl.get(i);
10524 if (conn.clientLabel != 0) {
10525 info.clientPackage = conn.binding.client.info.packageName;
10526 info.clientLabel = conn.clientLabel;
10527 return info;
10528 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010529 }
10530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010531 return info;
10532 }
10533
10534 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10535 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010536 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010537 synchronized (this) {
10538 ArrayList<ActivityManager.RunningServiceInfo> res
10539 = new ArrayList<ActivityManager.RunningServiceInfo>();
10540
Amith Yamasani742a6712011-05-04 14:49:28 -070010541 int userId = UserId.getUserId(Binder.getCallingUid());
10542 if (mServiceMap.getAllServices(userId).size() > 0) {
10543 Iterator<ServiceRecord> it
10544 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 while (it.hasNext() && res.size() < maxNum) {
10546 res.add(makeRunningServiceInfoLocked(it.next()));
10547 }
10548 }
10549
10550 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10551 ServiceRecord r = mRestartingServices.get(i);
10552 ActivityManager.RunningServiceInfo info =
10553 makeRunningServiceInfoLocked(r);
10554 info.restarting = r.nextRestartTime;
10555 res.add(info);
10556 }
10557
10558 return res;
10559 }
10560 }
10561
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010562 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010563 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010564 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010565 int userId = UserId.getUserId(Binder.getCallingUid());
10566 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010567 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010568 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10569 for (int i=0; i<conn.size(); i++) {
10570 if (conn.get(i).clientIntent != null) {
10571 return conn.get(i).clientIntent;
10572 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010573 }
10574 }
10575 }
10576 }
10577 return null;
10578 }
10579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 private final ServiceRecord findServiceLocked(ComponentName name,
10581 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010582 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010583 return r == token ? r : null;
10584 }
10585
10586 private final class ServiceLookupResult {
10587 final ServiceRecord record;
10588 final String permission;
10589
10590 ServiceLookupResult(ServiceRecord _record, String _permission) {
10591 record = _record;
10592 permission = _permission;
10593 }
10594 };
10595
10596 private ServiceLookupResult findServiceLocked(Intent service,
10597 String resolvedType) {
10598 ServiceRecord r = null;
10599 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010600 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 }
10602 if (r == null) {
10603 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010604 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 }
10606
10607 if (r == null) {
10608 try {
10609 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010610 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611 service, resolvedType, 0);
10612 ServiceInfo sInfo =
10613 rInfo != null ? rInfo.serviceInfo : null;
10614 if (sInfo == null) {
10615 return null;
10616 }
10617
10618 ComponentName name = new ComponentName(
10619 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010620 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010621 } catch (RemoteException ex) {
10622 // pm is in same process, this will never happen.
10623 }
10624 }
10625 if (r != null) {
10626 int callingPid = Binder.getCallingPid();
10627 int callingUid = Binder.getCallingUid();
10628 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010629 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010631 if (!r.exported) {
10632 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10633 + " from pid=" + callingPid
10634 + ", uid=" + callingUid
10635 + " that is not exported from uid " + r.appInfo.uid);
10636 return new ServiceLookupResult(null, "not exported from uid "
10637 + r.appInfo.uid);
10638 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010639 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010640 + " from pid=" + callingPid
10641 + ", uid=" + callingUid
10642 + " requires " + r.permission);
10643 return new ServiceLookupResult(null, r.permission);
10644 }
10645 return new ServiceLookupResult(r, null);
10646 }
10647 return null;
10648 }
10649
10650 private class ServiceRestarter implements Runnable {
10651 private ServiceRecord mService;
10652
10653 void setService(ServiceRecord service) {
10654 mService = service;
10655 }
10656
10657 public void run() {
10658 synchronized(ActivityManagerService.this) {
10659 performServiceRestartLocked(mService);
10660 }
10661 }
10662 }
10663
10664 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010665 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010667 if (DEBUG_SERVICE)
10668 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010669 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010671 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010672 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010674 if (r == null) {
10675 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010676 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010678 if (r == null) {
10679 try {
10680 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010681 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010682 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 ServiceInfo sInfo =
10684 rInfo != null ? rInfo.serviceInfo : null;
10685 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010686 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010687 ": not found");
10688 return null;
10689 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010690 if (userId > 0) {
10691 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 ComponentName name = new ComponentName(
10694 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010695 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010697 Intent.FilterComparison filter = new Intent.FilterComparison(
10698 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 ServiceRestarter res = new ServiceRestarter();
10700 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10701 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10702 synchronized (stats) {
10703 ss = stats.getServiceStatsLocked(
10704 sInfo.applicationInfo.uid, sInfo.packageName,
10705 sInfo.name);
10706 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010707 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010708 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010709 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10710 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010711
10712 // Make sure this component isn't in the pending list.
10713 int N = mPendingServices.size();
10714 for (int i=0; i<N; i++) {
10715 ServiceRecord pr = mPendingServices.get(i);
10716 if (pr.name.equals(name)) {
10717 mPendingServices.remove(i);
10718 i--;
10719 N--;
10720 }
10721 }
10722 }
10723 } catch (RemoteException ex) {
10724 // pm is in same process, this will never happen.
10725 }
10726 }
10727 if (r != null) {
10728 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010729 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010731 if (!r.exported) {
10732 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10733 + " from pid=" + callingPid
10734 + ", uid=" + callingUid
10735 + " that is not exported from uid " + r.appInfo.uid);
10736 return new ServiceLookupResult(null, "not exported from uid "
10737 + r.appInfo.uid);
10738 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010739 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010740 + " from pid=" + callingPid
10741 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 + " requires " + r.permission);
10743 return new ServiceLookupResult(null, r.permission);
10744 }
10745 return new ServiceLookupResult(r, null);
10746 }
10747 return null;
10748 }
10749
Dianne Hackborn287952c2010-09-22 22:34:31 -070010750 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10751 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10752 + why + " of " + r + " in app " + r.app);
10753 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10754 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 long now = SystemClock.uptimeMillis();
10756 if (r.executeNesting == 0 && r.app != null) {
10757 if (r.app.executingServices.size() == 0) {
10758 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10759 msg.obj = r.app;
10760 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10761 }
10762 r.app.executingServices.add(r);
10763 }
10764 r.executeNesting++;
10765 r.executingStart = now;
10766 }
10767
10768 private final void sendServiceArgsLocked(ServiceRecord r,
10769 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010770 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 if (N == 0) {
10772 return;
10773 }
10774
Dianne Hackborn39792d22010-08-19 18:01:52 -070010775 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010777 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010778 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10779 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010780 if (si.intent == null && N > 1) {
10781 // If somehow we got a dummy null intent in the middle,
10782 // then skip it. DO NOT skip a null intent when it is
10783 // the only one in the list -- this is to support the
10784 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010785 continue;
10786 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010787 si.deliveredTime = SystemClock.uptimeMillis();
10788 r.deliveredStarts.add(si);
10789 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010790 if (si.neededGrants != null) {
10791 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10792 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010793 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010794 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 if (!oomAdjusted) {
10796 oomAdjusted = true;
10797 updateOomAdjLocked(r.app);
10798 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010799 int flags = 0;
10800 if (si.deliveryCount > 0) {
10801 flags |= Service.START_FLAG_RETRY;
10802 }
10803 if (si.doneExecutingCount > 0) {
10804 flags |= Service.START_FLAG_REDELIVERY;
10805 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010806 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010807 } catch (RemoteException e) {
10808 // Remote process gone... we'll let the normal cleanup take
10809 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010810 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010811 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010812 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010813 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010814 break;
10815 }
10816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 }
10818
10819 private final boolean requestServiceBindingLocked(ServiceRecord r,
10820 IntentBindRecord i, boolean rebind) {
10821 if (r.app == null || r.app.thread == null) {
10822 // If service is not currently running, can't yet bind.
10823 return false;
10824 }
10825 if ((!i.requested || rebind) && i.apps.size() > 0) {
10826 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010827 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010828 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10829 if (!rebind) {
10830 i.requested = true;
10831 }
10832 i.hasBound = true;
10833 i.doRebind = false;
10834 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010835 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 return false;
10837 }
10838 }
10839 return true;
10840 }
10841
10842 private final void requestServiceBindingsLocked(ServiceRecord r) {
10843 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10844 while (bindings.hasNext()) {
10845 IntentBindRecord i = bindings.next();
10846 if (!requestServiceBindingLocked(r, i, false)) {
10847 break;
10848 }
10849 }
10850 }
10851
10852 private final void realStartServiceLocked(ServiceRecord r,
10853 ProcessRecord app) throws RemoteException {
10854 if (app.thread == null) {
10855 throw new RemoteException();
10856 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010857 if (DEBUG_MU)
10858 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010859 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010861 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862
10863 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010864 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010865 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866
10867 boolean created = false;
10868 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010869 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010870 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010871 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010872 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010873 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874 synchronized (r.stats.getBatteryStats()) {
10875 r.stats.startLaunchedLocked();
10876 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010877 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010878 app.thread.scheduleCreateService(r, r.serviceInfo,
10879 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010880 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 created = true;
10882 } finally {
10883 if (!created) {
10884 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010885 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 }
10887 }
10888
10889 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010890
10891 // If the service is in the started state, and there are no
10892 // pending arguments, then fake up one so its onStartCommand() will
10893 // be called.
10894 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010895 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010896 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010897 }
10898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010899 sendServiceArgsLocked(r, true);
10900 }
10901
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010902 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10903 boolean allowCancel) {
10904 boolean canceled = false;
10905
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010906 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010907 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010908 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010909
Dianne Hackborn070783f2010-12-29 16:46:28 -080010910 if ((r.serviceInfo.applicationInfo.flags
10911 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10912 minDuration /= 4;
10913 }
10914
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010915 // Any delivered but not yet finished starts should be put back
10916 // on the pending list.
10917 final int N = r.deliveredStarts.size();
10918 if (N > 0) {
10919 for (int i=N-1; i>=0; i--) {
10920 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010921 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010922 if (si.intent == null) {
10923 // We'll generate this again if needed.
10924 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10925 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10926 r.pendingStarts.add(0, si);
10927 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10928 dur *= 2;
10929 if (minDuration < dur) minDuration = dur;
10930 if (resetTime < dur) resetTime = dur;
10931 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010932 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010933 + r.name);
10934 canceled = true;
10935 }
10936 }
10937 r.deliveredStarts.clear();
10938 }
10939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940 r.totalRestartCount++;
10941 if (r.restartDelay == 0) {
10942 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010943 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 } else {
10945 // If it has been a "reasonably long time" since the service
10946 // was started, then reset our restart duration back to
10947 // the beginning, so we don't infinitely increase the duration
10948 // on a service that just occasionally gets killed (which is
10949 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010950 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010952 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010954 if ((r.serviceInfo.applicationInfo.flags
10955 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10956 // Services in peristent processes will restart much more
10957 // quickly, since they are pretty important. (Think SystemUI).
10958 r.restartDelay += minDuration/2;
10959 } else {
10960 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10961 if (r.restartDelay < minDuration) {
10962 r.restartDelay = minDuration;
10963 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 }
10966 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010967
10968 r.nextRestartTime = now + r.restartDelay;
10969
10970 // Make sure that we don't end up restarting a bunch of services
10971 // all at the same time.
10972 boolean repeat;
10973 do {
10974 repeat = false;
10975 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10976 ServiceRecord r2 = mRestartingServices.get(i);
10977 if (r2 != r && r.nextRestartTime
10978 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10979 && r.nextRestartTime
10980 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10981 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10982 r.restartDelay = r.nextRestartTime - now;
10983 repeat = true;
10984 break;
10985 }
10986 }
10987 } while (repeat);
10988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010989 if (!mRestartingServices.contains(r)) {
10990 mRestartingServices.add(r);
10991 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010992
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010993 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010995 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010996 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010998 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011000 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 r.shortName, r.restartDelay);
11002
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011003 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011004 }
11005
11006 final void performServiceRestartLocked(ServiceRecord r) {
11007 if (!mRestartingServices.contains(r)) {
11008 return;
11009 }
11010 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11011 }
11012
11013 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11014 if (r.restartDelay == 0) {
11015 return false;
11016 }
11017 r.resetRestartCounter();
11018 mRestartingServices.remove(r);
11019 mHandler.removeCallbacks(r.restarter);
11020 return true;
11021 }
11022
11023 private final boolean bringUpServiceLocked(ServiceRecord r,
11024 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011025 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 //r.dump(" ");
11027
Dianne Hackborn36124872009-10-08 16:22:03 -070011028 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 sendServiceArgsLocked(r, false);
11030 return true;
11031 }
11032
11033 if (!whileRestarting && r.restartDelay > 0) {
11034 // If waiting for a restart, then do nothing.
11035 return true;
11036 }
11037
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011038 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011040 // We are now bringing the service up, so no longer in the
11041 // restarting state.
11042 mRestartingServices.remove(r);
11043
Dianne Hackborne7f97212011-02-24 14:40:20 -080011044 // Service is now being launched, its package can't be stopped.
11045 try {
11046 AppGlobals.getPackageManager().setPackageStoppedState(
11047 r.packageName, false);
11048 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011049 } catch (IllegalArgumentException e) {
11050 Slog.w(TAG, "Failed trying to unstop package "
11051 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011052 }
11053
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011054 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011056 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011058 if (!isolated) {
11059 app = getProcessRecordLocked(appName, r.appInfo.uid);
11060 if (DEBUG_MU)
11061 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11062 if (app != null && app.thread != null) {
11063 try {
11064 app.addPackage(r.appInfo.packageName);
11065 realStartServiceLocked(r, app);
11066 return true;
11067 } catch (RemoteException e) {
11068 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11069 }
11070
11071 // If a dead object exception was thrown -- fall through to
11072 // restart the application.
11073 }
11074 } else {
11075 // If this service runs in an isolated process, then each time
11076 // we call startProcessLocked() we will get a new isolated
11077 // process, starting another process if we are currently waiting
11078 // for a previous process to come up. To deal with this, we store
11079 // in the service any current isolated process it is running in or
11080 // waiting to have come up.
11081 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 }
11083
Dianne Hackborn36124872009-10-08 16:22:03 -070011084 // Not running -- get it started, and enqueue this service record
11085 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011086 if (app == null) {
11087 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11088 "service", r.name, false, isolated)) == null) {
11089 Slog.w(TAG, "Unable to launch app "
11090 + r.appInfo.packageName + "/"
11091 + r.appInfo.uid + " for service "
11092 + r.intent.getIntent() + ": process is bad");
11093 bringDownServiceLocked(r, true);
11094 return false;
11095 }
11096 if (isolated) {
11097 r.isolatedProc = app;
11098 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011099 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 mPendingServices.add(r);
11103 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011105 return true;
11106 }
11107
11108 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011109 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 //r.dump(" ");
11111
11112 // Does it still need to run?
11113 if (!force && r.startRequested) {
11114 return;
11115 }
11116 if (r.connections.size() > 0) {
11117 if (!force) {
11118 // XXX should probably keep a count of the number of auto-create
11119 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011120 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011122 ArrayList<ConnectionRecord> cr = it.next();
11123 for (int i=0; i<cr.size(); i++) {
11124 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11125 return;
11126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011127 }
11128 }
11129 }
11130
11131 // Report to all of the connections that the service is no longer
11132 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011133 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011134 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011135 ArrayList<ConnectionRecord> c = it.next();
11136 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011137 ConnectionRecord cr = c.get(i);
11138 // There is still a connection to the service that is
11139 // being brought down. Mark it as dead.
11140 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011141 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011142 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011143 } catch (Exception e) {
11144 Slog.w(TAG, "Failure disconnecting service " + r.name +
11145 " to connection " + c.get(i).conn.asBinder() +
11146 " (in " + c.get(i).binding.client.processName + ")", e);
11147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148 }
11149 }
11150 }
11151
11152 // Tell the service that it has been unbound.
11153 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11154 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11155 while (it.hasNext()) {
11156 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011157 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 + ": hasBound=" + ibr.hasBound);
11159 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11160 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011161 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011162 updateOomAdjLocked(r.app);
11163 ibr.hasBound = false;
11164 r.app.thread.scheduleUnbindService(r,
11165 ibr.intent.getIntent());
11166 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011167 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011168 + r.shortName, e);
11169 serviceDoneExecutingLocked(r, true);
11170 }
11171 }
11172 }
11173 }
11174
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011175 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011176 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 System.identityHashCode(r), r.shortName,
11178 (r.app != null) ? r.app.pid : -1);
11179
Amith Yamasani742a6712011-05-04 14:49:28 -070011180 mServiceMap.removeServiceByName(r.name, r.userId);
11181 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011182 r.totalRestartCount = 0;
11183 unscheduleServiceRestartLocked(r);
11184
11185 // Also make sure it is not on the pending list.
11186 int N = mPendingServices.size();
11187 for (int i=0; i<N; i++) {
11188 if (mPendingServices.get(i) == r) {
11189 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011190 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011191 i--;
11192 N--;
11193 }
11194 }
11195
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011196 r.cancelNotification();
11197 r.isForeground = false;
11198 r.foregroundId = 0;
11199 r.foregroundNoti = null;
11200
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011201 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011202 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011203 r.pendingStarts.clear();
11204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 if (r.app != null) {
11206 synchronized (r.stats.getBatteryStats()) {
11207 r.stats.stopLaunchedLocked();
11208 }
11209 r.app.services.remove(r);
11210 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011212 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 mStoppingServices.add(r);
11214 updateOomAdjLocked(r.app);
11215 r.app.thread.scheduleStopService(r);
11216 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011217 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011218 + r.shortName, e);
11219 serviceDoneExecutingLocked(r, true);
11220 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011221 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011223 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011224 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 }
11226 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011227 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011228 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011229 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011230
11231 if (r.bindings.size() > 0) {
11232 r.bindings.clear();
11233 }
11234
11235 if (r.restarter instanceof ServiceRestarter) {
11236 ((ServiceRestarter)r.restarter).setService(null);
11237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011238 }
11239
11240 ComponentName startServiceLocked(IApplicationThread caller,
11241 Intent service, String resolvedType,
11242 int callingPid, int callingUid) {
11243 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011244 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 + " type=" + resolvedType + " args=" + service.getExtras());
11246
11247 if (caller != null) {
11248 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11249 if (callerApp == null) {
11250 throw new SecurityException(
11251 "Unable to find app for caller " + caller
11252 + " (pid=" + Binder.getCallingPid()
11253 + ") when starting service " + service);
11254 }
11255 }
11256
11257 ServiceLookupResult res =
11258 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011259 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 if (res == null) {
11261 return null;
11262 }
11263 if (res.record == null) {
11264 return new ComponentName("!", res.permission != null
11265 ? res.permission : "private to package");
11266 }
11267 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011268 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11269 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011271 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 }
11273 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011274 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011275 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011276 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011277 r.lastActivity = SystemClock.uptimeMillis();
11278 synchronized (r.stats.getBatteryStats()) {
11279 r.stats.startRunningLocked();
11280 }
11281 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11282 return new ComponentName("!", "Service process is bad");
11283 }
11284 return r.name;
11285 }
11286 }
11287
11288 public ComponentName startService(IApplicationThread caller, Intent service,
11289 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011290 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011291 // Refuse possible leaked file descriptors
11292 if (service != null && service.hasFileDescriptors() == true) {
11293 throw new IllegalArgumentException("File descriptors passed in Intent");
11294 }
11295
Amith Yamasani742a6712011-05-04 14:49:28 -070011296 if (DEBUG_SERVICE)
11297 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 synchronized(this) {
11299 final int callingPid = Binder.getCallingPid();
11300 final int callingUid = Binder.getCallingUid();
11301 final long origId = Binder.clearCallingIdentity();
11302 ComponentName res = startServiceLocked(caller, service,
11303 resolvedType, callingPid, callingUid);
11304 Binder.restoreCallingIdentity(origId);
11305 return res;
11306 }
11307 }
11308
11309 ComponentName startServiceInPackage(int uid,
11310 Intent service, String resolvedType) {
11311 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011312 if (DEBUG_SERVICE)
11313 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 final long origId = Binder.clearCallingIdentity();
11315 ComponentName res = startServiceLocked(null, service,
11316 resolvedType, -1, uid);
11317 Binder.restoreCallingIdentity(origId);
11318 return res;
11319 }
11320 }
11321
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011322 private void stopServiceLocked(ServiceRecord service) {
11323 synchronized (service.stats.getBatteryStats()) {
11324 service.stats.stopRunningLocked();
11325 }
11326 service.startRequested = false;
11327 service.callStart = false;
11328 bringDownServiceLocked(service, false);
11329 }
11330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 public int stopService(IApplicationThread caller, Intent service,
11332 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011333 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 // Refuse possible leaked file descriptors
11335 if (service != null && service.hasFileDescriptors() == true) {
11336 throw new IllegalArgumentException("File descriptors passed in Intent");
11337 }
11338
11339 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011340 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 + " type=" + resolvedType);
11342
11343 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11344 if (caller != null && callerApp == null) {
11345 throw new SecurityException(
11346 "Unable to find app for caller " + caller
11347 + " (pid=" + Binder.getCallingPid()
11348 + ") when stopping service " + service);
11349 }
11350
11351 // If this service is active, make sure it is stopped.
11352 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11353 if (r != null) {
11354 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011356 try {
11357 stopServiceLocked(r.record);
11358 } finally {
11359 Binder.restoreCallingIdentity(origId);
11360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011361 return 1;
11362 }
11363 return -1;
11364 }
11365 }
11366
11367 return 0;
11368 }
11369
11370 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011371 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 // Refuse possible leaked file descriptors
11373 if (service != null && service.hasFileDescriptors() == true) {
11374 throw new IllegalArgumentException("File descriptors passed in Intent");
11375 }
11376
11377 IBinder ret = null;
11378
11379 synchronized(this) {
11380 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11381
11382 if (r != null) {
11383 // r.record is null if findServiceLocked() failed the caller permission check
11384 if (r.record == null) {
11385 throw new SecurityException(
11386 "Permission Denial: Accessing service " + r.record.name
11387 + " from pid=" + Binder.getCallingPid()
11388 + ", uid=" + Binder.getCallingUid()
11389 + " requires " + r.permission);
11390 }
11391 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11392 if (ib != null) {
11393 ret = ib.binder;
11394 }
11395 }
11396 }
11397
11398 return ret;
11399 }
11400
11401 public boolean stopServiceToken(ComponentName className, IBinder token,
11402 int startId) {
11403 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011404 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011405 + " " + token + " startId=" + startId);
11406 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011407 if (r != null) {
11408 if (startId >= 0) {
11409 // Asked to only stop if done with all work. Note that
11410 // to avoid leaks, we will take this as dropping all
11411 // start items up to and including this one.
11412 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11413 if (si != null) {
11414 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011415 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11416 cur.removeUriPermissionsLocked();
11417 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011418 break;
11419 }
11420 }
11421 }
11422
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011423 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011424 return false;
11425 }
11426
11427 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011428 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011429 + " is last, but have " + r.deliveredStarts.size()
11430 + " remaining args");
11431 }
11432 }
11433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 synchronized (r.stats.getBatteryStats()) {
11435 r.stats.stopRunningLocked();
11436 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011437 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011438 }
11439 final long origId = Binder.clearCallingIdentity();
11440 bringDownServiceLocked(r, false);
11441 Binder.restoreCallingIdentity(origId);
11442 return true;
11443 }
11444 }
11445 return false;
11446 }
11447
11448 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011449 int id, Notification notification, boolean removeNotification) {
11450 final long origId = Binder.clearCallingIdentity();
11451 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011452 synchronized(this) {
11453 ServiceRecord r = findServiceLocked(className, token);
11454 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011455 if (id != 0) {
11456 if (notification == null) {
11457 throw new IllegalArgumentException("null notification");
11458 }
11459 if (r.foregroundId != id) {
11460 r.cancelNotification();
11461 r.foregroundId = id;
11462 }
11463 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11464 r.foregroundNoti = notification;
11465 r.isForeground = true;
11466 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467 if (r.app != null) {
11468 updateServiceForegroundLocked(r.app, true);
11469 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011470 } else {
11471 if (r.isForeground) {
11472 r.isForeground = false;
11473 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011474 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011475 updateServiceForegroundLocked(r.app, true);
11476 }
11477 }
11478 if (removeNotification) {
11479 r.cancelNotification();
11480 r.foregroundId = 0;
11481 r.foregroundNoti = null;
11482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 }
11484 }
11485 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011486 } finally {
11487 Binder.restoreCallingIdentity(origId);
11488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 }
11490
11491 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11492 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011493 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011494 if (sr.isForeground) {
11495 anyForeground = true;
11496 break;
11497 }
11498 }
11499 if (anyForeground != proc.foregroundServices) {
11500 proc.foregroundServices = anyForeground;
11501 if (oomAdj) {
11502 updateOomAdjLocked();
11503 }
11504 }
11505 }
11506
11507 public int bindService(IApplicationThread caller, IBinder token,
11508 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011509 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011510 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011511 // Refuse possible leaked file descriptors
11512 if (service != null && service.hasFileDescriptors() == true) {
11513 throw new IllegalArgumentException("File descriptors passed in Intent");
11514 }
11515
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011516 checkValidCaller(Binder.getCallingUid(), userId);
11517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011519 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011520 + " type=" + resolvedType + " conn=" + connection.asBinder()
11521 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011522 if (DEBUG_MU)
11523 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11524 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011525 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11526 if (callerApp == null) {
11527 throw new SecurityException(
11528 "Unable to find app for caller " + caller
11529 + " (pid=" + Binder.getCallingPid()
11530 + ") when binding service " + service);
11531 }
11532
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011533 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011535 activity = mMainStack.isInStackLocked(token);
11536 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011537 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 return 0;
11539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 }
11541
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011542 int clientLabel = 0;
11543 PendingIntent clientIntent = null;
11544
11545 if (callerApp.info.uid == Process.SYSTEM_UID) {
11546 // Hacky kind of thing -- allow system stuff to tell us
11547 // what they are, so we can report this elsewhere for
11548 // others to know why certain services are running.
11549 try {
11550 clientIntent = (PendingIntent)service.getParcelableExtra(
11551 Intent.EXTRA_CLIENT_INTENT);
11552 } catch (RuntimeException e) {
11553 }
11554 if (clientIntent != null) {
11555 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11556 if (clientLabel != 0) {
11557 // There are no useful extras in the intent, trash them.
11558 // System code calling with this stuff just needs to know
11559 // this will happen.
11560 service = service.cloneFilter();
11561 }
11562 }
11563 }
11564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011565 ServiceLookupResult res =
11566 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011567 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011568 if (res == null) {
11569 return 0;
11570 }
11571 if (res.record == null) {
11572 return -1;
11573 }
11574 ServiceRecord s = res.record;
11575
11576 final long origId = Binder.clearCallingIdentity();
11577
11578 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011579 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011580 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011581 }
11582
11583 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11584 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011585 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011586
11587 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011588 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11589 if (clist == null) {
11590 clist = new ArrayList<ConnectionRecord>();
11591 s.connections.put(binder, clist);
11592 }
11593 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 b.connections.add(c);
11595 if (activity != null) {
11596 if (activity.connections == null) {
11597 activity.connections = new HashSet<ConnectionRecord>();
11598 }
11599 activity.connections.add(c);
11600 }
11601 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011602 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11603 b.client.hasAboveClient = true;
11604 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011605 clist = mServiceConnections.get(binder);
11606 if (clist == null) {
11607 clist = new ArrayList<ConnectionRecord>();
11608 mServiceConnections.put(binder, clist);
11609 }
11610 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611
11612 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11613 s.lastActivity = SystemClock.uptimeMillis();
11614 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11615 return 0;
11616 }
11617 }
11618
11619 if (s.app != null) {
11620 // This could have made the service more important.
11621 updateOomAdjLocked(s.app);
11622 }
11623
Joe Onorato8a9b2202010-02-26 18:56:32 -080011624 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011625 + ": received=" + b.intent.received
11626 + " apps=" + b.intent.apps.size()
11627 + " doRebind=" + b.intent.doRebind);
11628
11629 if (s.app != null && b.intent.received) {
11630 // Service is already running, so we can immediately
11631 // publish the connection.
11632 try {
11633 c.conn.connected(s.name, b.intent.binder);
11634 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011635 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 + " to connection " + c.conn.asBinder()
11637 + " (in " + c.binding.client.processName + ")", e);
11638 }
11639
11640 // If this is the first app connected back to this binding,
11641 // and the service had previously asked to be told when
11642 // rebound, then do so.
11643 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11644 requestServiceBindingLocked(s, b.intent, true);
11645 }
11646 } else if (!b.intent.requested) {
11647 requestServiceBindingLocked(s, b.intent, false);
11648 }
11649
11650 Binder.restoreCallingIdentity(origId);
11651 }
11652
11653 return 1;
11654 }
11655
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011656 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011657 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011658 IBinder binder = c.conn.asBinder();
11659 AppBindRecord b = c.binding;
11660 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011661 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11662 if (clist != null) {
11663 clist.remove(c);
11664 if (clist.size() == 0) {
11665 s.connections.remove(binder);
11666 }
11667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011668 b.connections.remove(c);
11669 if (c.activity != null && c.activity != skipAct) {
11670 if (c.activity.connections != null) {
11671 c.activity.connections.remove(c);
11672 }
11673 }
11674 if (b.client != skipApp) {
11675 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011676 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11677 b.client.updateHasAboveClientLocked();
11678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011679 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011680 clist = mServiceConnections.get(binder);
11681 if (clist != null) {
11682 clist.remove(c);
11683 if (clist.size() == 0) {
11684 mServiceConnections.remove(binder);
11685 }
11686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687
11688 if (b.connections.size() == 0) {
11689 b.intent.apps.remove(b.client);
11690 }
11691
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011692 if (!c.serviceDead) {
11693 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11694 + ": shouldUnbind=" + b.intent.hasBound);
11695 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11696 && b.intent.hasBound) {
11697 try {
11698 bumpServiceExecutingLocked(s, "unbind");
11699 updateOomAdjLocked(s.app);
11700 b.intent.hasBound = false;
11701 // Assume the client doesn't want to know about a rebind;
11702 // we will deal with that later if it asks for one.
11703 b.intent.doRebind = false;
11704 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11705 } catch (Exception e) {
11706 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11707 serviceDoneExecutingLocked(s, true);
11708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011710
11711 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11712 bringDownServiceLocked(s, false);
11713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 }
11715 }
11716
11717 public boolean unbindService(IServiceConnection connection) {
11718 synchronized (this) {
11719 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011720 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011721 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11722 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011723 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 + connection.asBinder());
11725 return false;
11726 }
11727
11728 final long origId = Binder.clearCallingIdentity();
11729
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011730 while (clist.size() > 0) {
11731 ConnectionRecord r = clist.get(0);
11732 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011733
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011734 if (r.binding.service.app != null) {
11735 // This could have made the service less important.
11736 updateOomAdjLocked(r.binding.service.app);
11737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011738 }
11739
11740 Binder.restoreCallingIdentity(origId);
11741 }
11742
11743 return true;
11744 }
11745
11746 public void publishService(IBinder token, Intent intent, IBinder service) {
11747 // Refuse possible leaked file descriptors
11748 if (intent != null && intent.hasFileDescriptors() == true) {
11749 throw new IllegalArgumentException("File descriptors passed in Intent");
11750 }
11751
11752 synchronized(this) {
11753 if (!(token instanceof ServiceRecord)) {
11754 throw new IllegalArgumentException("Invalid service token");
11755 }
11756 ServiceRecord r = (ServiceRecord)token;
11757
11758 final long origId = Binder.clearCallingIdentity();
11759
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011760 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761 + " " + intent + ": " + service);
11762 if (r != null) {
11763 Intent.FilterComparison filter
11764 = new Intent.FilterComparison(intent);
11765 IntentBindRecord b = r.bindings.get(filter);
11766 if (b != null && !b.received) {
11767 b.binder = service;
11768 b.requested = true;
11769 b.received = true;
11770 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011771 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011772 = r.connections.values().iterator();
11773 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011774 ArrayList<ConnectionRecord> clist = it.next();
11775 for (int i=0; i<clist.size(); i++) {
11776 ConnectionRecord c = clist.get(i);
11777 if (!filter.equals(c.binding.intent.intent)) {
11778 if (DEBUG_SERVICE) Slog.v(
11779 TAG, "Not publishing to: " + c);
11780 if (DEBUG_SERVICE) Slog.v(
11781 TAG, "Bound intent: " + c.binding.intent.intent);
11782 if (DEBUG_SERVICE) Slog.v(
11783 TAG, "Published intent: " + intent);
11784 continue;
11785 }
11786 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11787 try {
11788 c.conn.connected(r.name, service);
11789 } catch (Exception e) {
11790 Slog.w(TAG, "Failure sending service " + r.name +
11791 " to connection " + c.conn.asBinder() +
11792 " (in " + c.binding.client.processName + ")", e);
11793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011794 }
11795 }
11796 }
11797 }
11798
11799 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11800
11801 Binder.restoreCallingIdentity(origId);
11802 }
11803 }
11804 }
11805
11806 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11807 // Refuse possible leaked file descriptors
11808 if (intent != null && intent.hasFileDescriptors() == true) {
11809 throw new IllegalArgumentException("File descriptors passed in Intent");
11810 }
11811
11812 synchronized(this) {
11813 if (!(token instanceof ServiceRecord)) {
11814 throw new IllegalArgumentException("Invalid service token");
11815 }
11816 ServiceRecord r = (ServiceRecord)token;
11817
11818 final long origId = Binder.clearCallingIdentity();
11819
11820 if (r != null) {
11821 Intent.FilterComparison filter
11822 = new Intent.FilterComparison(intent);
11823 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011824 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011825 + " at " + b + ": apps="
11826 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011827
11828 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011829 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011830 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831 // Applications have already bound since the last
11832 // unbind, so just rebind right here.
11833 requestServiceBindingLocked(r, b, true);
11834 } else {
11835 // Note to tell the service the next time there is
11836 // a new client.
11837 b.doRebind = true;
11838 }
11839 }
11840
Per Edelberg78f9fff2010-08-30 20:01:35 +020011841 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842
11843 Binder.restoreCallingIdentity(origId);
11844 }
11845 }
11846 }
11847
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011848 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011849 synchronized(this) {
11850 if (!(token instanceof ServiceRecord)) {
11851 throw new IllegalArgumentException("Invalid service token");
11852 }
11853 ServiceRecord r = (ServiceRecord)token;
11854 boolean inStopping = mStoppingServices.contains(token);
11855 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011857 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011858 + " with incorrect token: given " + token
11859 + ", expected " + r);
11860 return;
11861 }
11862
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011863 if (type == 1) {
11864 // This is a call from a service start... take care of
11865 // book-keeping.
11866 r.callStart = true;
11867 switch (res) {
11868 case Service.START_STICKY_COMPATIBILITY:
11869 case Service.START_STICKY: {
11870 // We are done with the associated start arguments.
11871 r.findDeliveredStart(startId, true);
11872 // Don't stop if killed.
11873 r.stopIfKilled = false;
11874 break;
11875 }
11876 case Service.START_NOT_STICKY: {
11877 // We are done with the associated start arguments.
11878 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011879 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011880 // There is no more work, and this service
11881 // doesn't want to hang around if killed.
11882 r.stopIfKilled = true;
11883 }
11884 break;
11885 }
11886 case Service.START_REDELIVER_INTENT: {
11887 // We'll keep this item until they explicitly
11888 // call stop for it, but keep track of the fact
11889 // that it was delivered.
11890 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11891 if (si != null) {
11892 si.deliveryCount = 0;
11893 si.doneExecutingCount++;
11894 // Don't stop if killed.
11895 r.stopIfKilled = true;
11896 }
11897 break;
11898 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011899 case Service.START_TASK_REMOVED_COMPLETE: {
11900 // Special processing for onTaskRemoved(). Don't
11901 // impact normal onStartCommand() processing.
11902 r.findDeliveredStart(startId, true);
11903 break;
11904 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011905 default:
11906 throw new IllegalArgumentException(
11907 "Unknown service start result: " + res);
11908 }
11909 if (res == Service.START_STICKY_COMPATIBILITY) {
11910 r.callStart = false;
11911 }
11912 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011913 if (DEBUG_MU)
11914 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11915 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011916 final long origId = Binder.clearCallingIdentity();
11917 serviceDoneExecutingLocked(r, inStopping);
11918 Binder.restoreCallingIdentity(origId);
11919 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011920 Slog.w(TAG, "Done executing unknown service from pid "
11921 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 }
11923 }
11924 }
11925
11926 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011927 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11928 + ": nesting=" + r.executeNesting
11929 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011930 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011931 r.executeNesting--;
11932 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011933 if (DEBUG_SERVICE) Slog.v(TAG,
11934 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011935 r.app.executingServices.remove(r);
11936 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011937 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11938 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11940 }
11941 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011942 if (DEBUG_SERVICE) Slog.v(TAG,
11943 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011945 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011946 }
11947 updateOomAdjLocked(r.app);
11948 }
11949 }
11950
11951 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011952 String anrMessage = null;
11953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011954 synchronized(this) {
11955 if (proc.executingServices.size() == 0 || proc.thread == null) {
11956 return;
11957 }
11958 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11959 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11960 ServiceRecord timeout = null;
11961 long nextTime = 0;
11962 while (it.hasNext()) {
11963 ServiceRecord sr = it.next();
11964 if (sr.executingStart < maxTime) {
11965 timeout = sr;
11966 break;
11967 }
11968 if (sr.executingStart > nextTime) {
11969 nextTime = sr.executingStart;
11970 }
11971 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011972 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011973 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011974 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 } else {
11976 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11977 msg.obj = proc;
11978 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11979 }
11980 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011981
11982 if (anrMessage != null) {
11983 appNotResponding(proc, null, null, anrMessage);
11984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011985 }
11986
11987 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011988 // BACKUP AND RESTORE
11989 // =========================================================
11990
11991 // Cause the target app to be launched if necessary and its backup agent
11992 // instantiated. The backup agent will invoke backupAgentCreated() on the
11993 // activity manager to announce its creation.
11994 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011995 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011996 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11997
11998 synchronized(this) {
11999 // !!! TODO: currently no check here that we're already bound
12000 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12001 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12002 synchronized (stats) {
12003 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12004 }
12005
Dianne Hackborne7f97212011-02-24 14:40:20 -080012006 // Backup agent is now in use, its package can't be stopped.
12007 try {
12008 AppGlobals.getPackageManager().setPackageStoppedState(
12009 app.packageName, false);
12010 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012011 } catch (IllegalArgumentException e) {
12012 Slog.w(TAG, "Failed trying to unstop package "
12013 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012014 }
12015
Christopher Tate181fafa2009-05-14 11:12:14 -070012016 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012017 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12018 ? new ComponentName(app.packageName, app.backupAgentName)
12019 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012020 // startProcessLocked() returns existing proc's record if it's already running
12021 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012022 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012023 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012024 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012025 return false;
12026 }
12027
12028 r.app = proc;
12029 mBackupTarget = r;
12030 mBackupAppName = app.packageName;
12031
Christopher Tate6fa95972009-06-05 18:43:55 -070012032 // Try not to kill the process during backup
12033 updateOomAdjLocked(proc);
12034
Christopher Tate181fafa2009-05-14 11:12:14 -070012035 // If the process is already attached, schedule the creation of the backup agent now.
12036 // If it is not yet live, this will be done when it attaches to the framework.
12037 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012038 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012039 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012040 proc.thread.scheduleCreateBackupAgent(app,
12041 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012042 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012043 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012044 }
12045 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012046 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012047 }
12048 // Invariants: at this point, the target app process exists and the application
12049 // is either already running or in the process of coming up. mBackupTarget and
12050 // mBackupAppName describe the app, so that when it binds back to the AM we
12051 // know that it's scheduled for a backup-agent operation.
12052 }
12053
12054 return true;
12055 }
12056
12057 // A backup agent has just come up
12058 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012059 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012060 + " = " + agent);
12061
12062 synchronized(this) {
12063 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012064 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012065 return;
12066 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012067 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012068
Dianne Hackborn06740692010-09-22 22:46:21 -070012069 long oldIdent = Binder.clearCallingIdentity();
12070 try {
12071 IBackupManager bm = IBackupManager.Stub.asInterface(
12072 ServiceManager.getService(Context.BACKUP_SERVICE));
12073 bm.agentConnected(agentPackageName, agent);
12074 } catch (RemoteException e) {
12075 // can't happen; the backup manager service is local
12076 } catch (Exception e) {
12077 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12078 e.printStackTrace();
12079 } finally {
12080 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012081 }
12082 }
12083
12084 // done with this agent
12085 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012086 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012087 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012088 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012089 return;
12090 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012091
12092 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012093 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012094 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012095 return;
12096 }
12097
Christopher Tate181fafa2009-05-14 11:12:14 -070012098 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012099 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012100 return;
12101 }
12102
Christopher Tate6fa95972009-06-05 18:43:55 -070012103 ProcessRecord proc = mBackupTarget.app;
12104 mBackupTarget = null;
12105 mBackupAppName = null;
12106
12107 // Not backing this app up any more; reset its OOM adjustment
12108 updateOomAdjLocked(proc);
12109
Christopher Tatec7b31e32009-06-10 15:49:30 -070012110 // If the app crashed during backup, 'thread' will be null here
12111 if (proc.thread != null) {
12112 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012113 proc.thread.scheduleDestroyBackupAgent(appInfo,
12114 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012115 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012116 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012117 e.printStackTrace();
12118 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012119 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012120 }
12121 }
12122 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 // BROADCASTS
12124 // =========================================================
12125
Josh Bartel7f208742010-02-25 11:01:44 -060012126 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 List cur) {
12128 final ContentResolver resolver = mContext.getContentResolver();
12129 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12130 if (list == null) {
12131 return cur;
12132 }
12133 int N = list.size();
12134 for (int i=0; i<N; i++) {
12135 Intent intent = list.get(i);
12136 if (filter.match(resolver, intent, true, TAG) >= 0) {
12137 if (cur == null) {
12138 cur = new ArrayList<Intent>();
12139 }
12140 cur.add(intent);
12141 }
12142 }
12143 return cur;
12144 }
12145
Christopher Tatef46723b2012-01-26 14:19:24 -080012146 boolean isPendingBroadcastProcessLocked(int pid) {
12147 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12148 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012150
Christopher Tatef46723b2012-01-26 14:19:24 -080012151 void skipPendingBroadcastLocked(int pid) {
12152 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12153 for (BroadcastQueue queue : mBroadcastQueues) {
12154 queue.skipPendingBroadcastLocked(pid);
12155 }
12156 }
12157
12158 // The app just attached; send any pending broadcasts that it should receive
12159 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12160 boolean didSomething = false;
12161 for (BroadcastQueue queue : mBroadcastQueues) {
12162 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012163 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012164 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012165 }
12166
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012167 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012168 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012169 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012170 synchronized(this) {
12171 ProcessRecord callerApp = null;
12172 if (caller != null) {
12173 callerApp = getRecordForAppLocked(caller);
12174 if (callerApp == null) {
12175 throw new SecurityException(
12176 "Unable to find app for caller " + caller
12177 + " (pid=" + Binder.getCallingPid()
12178 + ") when registering receiver " + receiver);
12179 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012180 if (callerApp.info.uid != Process.SYSTEM_UID &&
12181 !callerApp.pkgList.contains(callerPackage)) {
12182 throw new SecurityException("Given caller package " + callerPackage
12183 + " is not running in process " + callerApp);
12184 }
12185 } else {
12186 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012187 }
12188
12189 List allSticky = null;
12190
12191 // Look for any matching sticky broadcasts...
12192 Iterator actions = filter.actionsIterator();
12193 if (actions != null) {
12194 while (actions.hasNext()) {
12195 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012196 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 }
12198 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012199 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012200 }
12201
12202 // The first sticky in the list is returned directly back to
12203 // the client.
12204 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12205
Joe Onorato8a9b2202010-02-26 18:56:32 -080012206 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012207 + ": " + sticky);
12208
12209 if (receiver == null) {
12210 return sticky;
12211 }
12212
12213 ReceiverList rl
12214 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12215 if (rl == null) {
12216 rl = new ReceiverList(this, callerApp,
12217 Binder.getCallingPid(),
12218 Binder.getCallingUid(), receiver);
12219 if (rl.app != null) {
12220 rl.app.receivers.add(rl);
12221 } else {
12222 try {
12223 receiver.asBinder().linkToDeath(rl, 0);
12224 } catch (RemoteException e) {
12225 return sticky;
12226 }
12227 rl.linkedToDeath = true;
12228 }
12229 mRegisteredReceivers.put(receiver.asBinder(), rl);
12230 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012231 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012232 rl.add(bf);
12233 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012234 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 }
12236 mReceiverResolver.addFilter(bf);
12237
12238 // Enqueue broadcasts for all existing stickies that match
12239 // this filter.
12240 if (allSticky != null) {
12241 ArrayList receivers = new ArrayList();
12242 receivers.add(bf);
12243
12244 int N = allSticky.size();
12245 for (int i=0; i<N; i++) {
12246 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012247 BroadcastQueue queue = broadcastQueueForIntent(intent);
12248 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012250 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012251 queue.enqueueParallelBroadcastLocked(r);
12252 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
12254 }
12255
12256 return sticky;
12257 }
12258 }
12259
12260 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012261 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012262
Christopher Tatef46723b2012-01-26 14:19:24 -080012263 final long origId = Binder.clearCallingIdentity();
12264 try {
12265 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012266
Christopher Tatef46723b2012-01-26 14:19:24 -080012267 synchronized(this) {
12268 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012269 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012270 if (rl != null) {
12271 if (rl.curBroadcast != null) {
12272 BroadcastRecord r = rl.curBroadcast;
12273 final boolean doNext = finishReceiverLocked(
12274 receiver.asBinder(), r.resultCode, r.resultData,
12275 r.resultExtras, r.resultAbort, true);
12276 if (doNext) {
12277 doTrim = true;
12278 r.queue.processNextBroadcast(false);
12279 }
12280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012281
Christopher Tatef46723b2012-01-26 14:19:24 -080012282 if (rl.app != null) {
12283 rl.app.receivers.remove(rl);
12284 }
12285 removeReceiverLocked(rl);
12286 if (rl.linkedToDeath) {
12287 rl.linkedToDeath = false;
12288 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012290 }
12291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012292
Christopher Tatef46723b2012-01-26 14:19:24 -080012293 // If we actually concluded any broadcasts, we might now be able
12294 // to trim the recipients' apps from our working set
12295 if (doTrim) {
12296 trimApplications();
12297 return;
12298 }
12299
12300 } finally {
12301 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012303 }
12304
12305 void removeReceiverLocked(ReceiverList rl) {
12306 mRegisteredReceivers.remove(rl.receiver.asBinder());
12307 int N = rl.size();
12308 for (int i=0; i<N; i++) {
12309 mReceiverResolver.removeFilter(rl.get(i));
12310 }
12311 }
12312
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012313 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12314 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12315 ProcessRecord r = mLruProcesses.get(i);
12316 if (r.thread != null) {
12317 try {
12318 r.thread.dispatchPackageBroadcast(cmd, packages);
12319 } catch (RemoteException ex) {
12320 }
12321 }
12322 }
12323 }
12324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012325 private final int broadcastIntentLocked(ProcessRecord callerApp,
12326 String callerPackage, Intent intent, String resolvedType,
12327 IIntentReceiver resultTo, int resultCode, String resultData,
12328 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012329 boolean ordered, boolean sticky, int callingPid, int callingUid,
12330 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012331 intent = new Intent(intent);
12332
Dianne Hackborne7f97212011-02-24 14:40:20 -080012333 // By default broadcasts do not go to stopped apps.
12334 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12335
Joe Onorato8a9b2202010-02-26 18:56:32 -080012336 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012337 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12338 + " ordered=" + ordered);
12339 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012340 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341 }
12342
12343 // Handle special intents: if this broadcast is from the package
12344 // manager about a package being removed, we need to remove all of
12345 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012346 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012347 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012348 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12349 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012350 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012351 || uidRemoved) {
12352 if (checkComponentPermission(
12353 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012354 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012355 == PackageManager.PERMISSION_GRANTED) {
12356 if (uidRemoved) {
12357 final Bundle intentExtras = intent.getExtras();
12358 final int uid = intentExtras != null
12359 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12360 if (uid >= 0) {
12361 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12362 synchronized (bs) {
12363 bs.removeUidStatsLocked(uid);
12364 }
12365 }
12366 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012367 // If resources are unvailble just force stop all
12368 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012369 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012370 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12371 if (list != null && (list.length > 0)) {
12372 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012373 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012374 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012375 sendPackageBroadcastLocked(
12376 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012377 }
12378 } else {
12379 Uri data = intent.getData();
12380 String ssp;
12381 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12382 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12383 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012384 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012385 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012386 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012387 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12388 new String[] {ssp});
12389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 }
12391 }
12392 }
12393 } else {
12394 String msg = "Permission Denial: " + intent.getAction()
12395 + " broadcast from " + callerPackage + " (pid=" + callingPid
12396 + ", uid=" + callingUid + ")"
12397 + " requires "
12398 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012399 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012400 throw new SecurityException(msg);
12401 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012402
12403 // Special case for adding a package: by default turn on compatibility
12404 // mode.
12405 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012406 Uri data = intent.getData();
12407 String ssp;
12408 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12409 mCompatModePackages.handlePackageAddedLocked(ssp,
12410 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012412 }
12413
12414 /*
12415 * If this is the time zone changed action, queue up a message that will reset the timezone
12416 * of all currently running processes. This message will get queued up before the broadcast
12417 * happens.
12418 */
12419 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12420 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12421 }
12422
Robert Greenwalt03595d02010-11-02 14:08:23 -070012423 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12424 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12425 }
12426
Robert Greenwalt434203a2010-10-11 16:00:27 -070012427 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12428 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12429 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12430 }
12431
Dianne Hackborn854060af2009-07-09 18:14:31 -070012432 /*
12433 * Prevent non-system code (defined here to be non-persistent
12434 * processes) from sending protected broadcasts.
12435 */
12436 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12437 || callingUid == Process.SHELL_UID || callingUid == 0) {
12438 // Always okay.
12439 } else if (callerApp == null || !callerApp.persistent) {
12440 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012441 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012442 intent.getAction())) {
12443 String msg = "Permission Denial: not allowed to send broadcast "
12444 + intent.getAction() + " from pid="
12445 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012446 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012447 throw new SecurityException(msg);
12448 }
12449 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012450 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012451 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012452 }
12453 }
12454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 // Add to the sticky list if requested.
12456 if (sticky) {
12457 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12458 callingPid, callingUid)
12459 != PackageManager.PERMISSION_GRANTED) {
12460 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12461 + callingPid + ", uid=" + callingUid
12462 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012463 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012464 throw new SecurityException(msg);
12465 }
12466 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012467 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012468 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012469 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 }
12471 if (intent.getComponent() != null) {
12472 throw new SecurityException(
12473 "Sticky broadcasts can't target a specific component");
12474 }
12475 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12476 if (list == null) {
12477 list = new ArrayList<Intent>();
12478 mStickyBroadcasts.put(intent.getAction(), list);
12479 }
12480 int N = list.size();
12481 int i;
12482 for (i=0; i<N; i++) {
12483 if (intent.filterEquals(list.get(i))) {
12484 // This sticky already exists, replace it.
12485 list.set(i, new Intent(intent));
12486 break;
12487 }
12488 }
12489 if (i >= N) {
12490 list.add(new Intent(intent));
12491 }
12492 }
12493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012494 // Figure out who all will receive this broadcast.
12495 List receivers = null;
12496 List<BroadcastFilter> registeredReceivers = null;
12497 try {
12498 if (intent.getComponent() != null) {
12499 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012500 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012501 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012502 if (ai != null) {
12503 receivers = new ArrayList();
12504 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012505 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 receivers.add(ri);
12507 }
12508 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012509 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012510 // Need to resolve the intent to interested receivers...
12511 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12512 == 0) {
12513 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012514 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012515 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012516 }
Mihai Preda074edef2009-05-18 17:13:31 +020012517 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518 }
12519 } catch (RemoteException ex) {
12520 // pm is in same process, this will never happen.
12521 }
12522
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012523 final boolean replacePending =
12524 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12525
Joe Onorato8a9b2202010-02-26 18:56:32 -080012526 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012527 + " replacePending=" + replacePending);
12528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12530 if (!ordered && NR > 0) {
12531 // If we are not serializing this broadcast, then send the
12532 // registered receivers separately so they don't wait for the
12533 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012534 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12535 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012536 callerPackage, callingPid, callingUid, requiredPermission,
12537 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012538 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012539 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012540 TAG, "Enqueueing parallel broadcast " + r);
12541 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012542 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012543 queue.enqueueParallelBroadcastLocked(r);
12544 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012546 registeredReceivers = null;
12547 NR = 0;
12548 }
12549
12550 // Merge into one list.
12551 int ir = 0;
12552 if (receivers != null) {
12553 // A special case for PACKAGE_ADDED: do not allow the package
12554 // being added to see this broadcast. This prevents them from
12555 // using this as a back door to get run as soon as they are
12556 // installed. Maybe in the future we want to have a special install
12557 // broadcast or such for apps, but we'd like to deliberately make
12558 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012559 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012560 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12561 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12562 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012563 Uri data = intent.getData();
12564 if (data != null) {
12565 String pkgName = data.getSchemeSpecificPart();
12566 if (pkgName != null) {
12567 skipPackages = new String[] { pkgName };
12568 }
12569 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012570 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012571 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012572 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012573 if (skipPackages != null && (skipPackages.length > 0)) {
12574 for (String skipPackage : skipPackages) {
12575 if (skipPackage != null) {
12576 int NT = receivers.size();
12577 for (int it=0; it<NT; it++) {
12578 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12579 if (curt.activityInfo.packageName.equals(skipPackage)) {
12580 receivers.remove(it);
12581 it--;
12582 NT--;
12583 }
12584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 }
12586 }
12587 }
12588
12589 int NT = receivers != null ? receivers.size() : 0;
12590 int it = 0;
12591 ResolveInfo curt = null;
12592 BroadcastFilter curr = null;
12593 while (it < NT && ir < NR) {
12594 if (curt == null) {
12595 curt = (ResolveInfo)receivers.get(it);
12596 }
12597 if (curr == null) {
12598 curr = registeredReceivers.get(ir);
12599 }
12600 if (curr.getPriority() >= curt.priority) {
12601 // Insert this broadcast record into the final list.
12602 receivers.add(it, curr);
12603 ir++;
12604 curr = null;
12605 it++;
12606 NT++;
12607 } else {
12608 // Skip to the next ResolveInfo in the final list.
12609 it++;
12610 curt = null;
12611 }
12612 }
12613 }
12614 while (ir < NR) {
12615 if (receivers == null) {
12616 receivers = new ArrayList();
12617 }
12618 receivers.add(registeredReceivers.get(ir));
12619 ir++;
12620 }
12621
12622 if ((receivers != null && receivers.size() > 0)
12623 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012624 BroadcastQueue queue = broadcastQueueForIntent(intent);
12625 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012626 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012627 receivers, resultTo, resultCode, resultData, map, ordered,
12628 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012629 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012630 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012631 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 if (DEBUG_BROADCAST) {
12633 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012634 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012635 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012636 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012637 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012638 queue.enqueueOrderedBroadcastLocked(r);
12639 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012641 }
12642
Dianne Hackborna4972e92012-03-14 10:38:05 -070012643 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012644 }
12645
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012646 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012647 // Refuse possible leaked file descriptors
12648 if (intent != null && intent.hasFileDescriptors() == true) {
12649 throw new IllegalArgumentException("File descriptors passed in Intent");
12650 }
12651
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012652 int flags = intent.getFlags();
12653
12654 if (!mProcessesReady) {
12655 // if the caller really truly claims to know what they're doing, go
12656 // ahead and allow the broadcast without launching any receivers
12657 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12658 intent = new Intent(intent);
12659 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12660 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12661 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12662 + " before boot completion");
12663 throw new IllegalStateException("Cannot broadcast before boot completed");
12664 }
12665 }
12666
12667 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12668 throw new IllegalArgumentException(
12669 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12670 }
12671
12672 return intent;
12673 }
12674
12675 public final int broadcastIntent(IApplicationThread caller,
12676 Intent intent, String resolvedType, IIntentReceiver resultTo,
12677 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012678 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012679 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012681 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12684 final int callingPid = Binder.getCallingPid();
12685 final int callingUid = Binder.getCallingUid();
12686 final long origId = Binder.clearCallingIdentity();
12687 int res = broadcastIntentLocked(callerApp,
12688 callerApp != null ? callerApp.info.packageName : null,
12689 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012690 resultCode, resultData, map, requiredPermission, serialized, sticky,
12691 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012692 Binder.restoreCallingIdentity(origId);
12693 return res;
12694 }
12695 }
12696
12697 int broadcastIntentInPackage(String packageName, int uid,
12698 Intent intent, String resolvedType, IIntentReceiver resultTo,
12699 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012700 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012701 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012702 intent = verifyBroadcastLocked(intent);
12703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012704 final long origId = Binder.clearCallingIdentity();
12705 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12706 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012707 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708 Binder.restoreCallingIdentity(origId);
12709 return res;
12710 }
12711 }
12712
Amith Yamasani742a6712011-05-04 14:49:28 -070012713 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12714 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012715 // Refuse possible leaked file descriptors
12716 if (intent != null && intent.hasFileDescriptors() == true) {
12717 throw new IllegalArgumentException("File descriptors passed in Intent");
12718 }
12719
12720 synchronized(this) {
12721 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12722 != PackageManager.PERMISSION_GRANTED) {
12723 String msg = "Permission Denial: unbroadcastIntent() from pid="
12724 + Binder.getCallingPid()
12725 + ", uid=" + Binder.getCallingUid()
12726 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012727 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012728 throw new SecurityException(msg);
12729 }
12730 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12731 if (list != null) {
12732 int N = list.size();
12733 int i;
12734 for (i=0; i<N; i++) {
12735 if (intent.filterEquals(list.get(i))) {
12736 list.remove(i);
12737 break;
12738 }
12739 }
12740 }
12741 }
12742 }
12743
12744 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12745 String resultData, Bundle resultExtras, boolean resultAbort,
12746 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012747 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12748 if (r == null) {
12749 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012750 return false;
12751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752
Christopher Tatef46723b2012-01-26 14:19:24 -080012753 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12754 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012755 }
12756
12757 public void finishReceiver(IBinder who, int resultCode, String resultData,
12758 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012759 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012760
12761 // Refuse possible leaked file descriptors
12762 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12763 throw new IllegalArgumentException("File descriptors passed in Bundle");
12764 }
12765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012766 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012767 try {
12768 boolean doNext = false;
12769 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012770
Christopher Tatef46723b2012-01-26 14:19:24 -080012771 synchronized(this) {
12772 r = broadcastRecordForReceiverLocked(who);
12773 if (r != null) {
12774 doNext = r.queue.finishReceiverLocked(r, resultCode,
12775 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012777 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012778
Christopher Tatef46723b2012-01-26 14:19:24 -080012779 if (doNext) {
12780 r.queue.processNextBroadcast(false);
12781 }
12782 trimApplications();
12783 } finally {
12784 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012788 // =========================================================
12789 // INSTRUMENTATION
12790 // =========================================================
12791
12792 public boolean startInstrumentation(ComponentName className,
12793 String profileFile, int flags, Bundle arguments,
12794 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012795 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 // Refuse possible leaked file descriptors
12797 if (arguments != null && arguments.hasFileDescriptors()) {
12798 throw new IllegalArgumentException("File descriptors passed in Bundle");
12799 }
12800
12801 synchronized(this) {
12802 InstrumentationInfo ii = null;
12803 ApplicationInfo ai = null;
12804 try {
12805 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012806 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012807 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012808 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012809 } catch (PackageManager.NameNotFoundException e) {
12810 }
12811 if (ii == null) {
12812 reportStartInstrumentationFailure(watcher, className,
12813 "Unable to find instrumentation info for: " + className);
12814 return false;
12815 }
12816 if (ai == null) {
12817 reportStartInstrumentationFailure(watcher, className,
12818 "Unable to find instrumentation target package: " + ii.targetPackage);
12819 return false;
12820 }
12821
12822 int match = mContext.getPackageManager().checkSignatures(
12823 ii.targetPackage, ii.packageName);
12824 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12825 String msg = "Permission Denial: starting instrumentation "
12826 + className + " from pid="
12827 + Binder.getCallingPid()
12828 + ", uid=" + Binder.getCallingPid()
12829 + " not allowed because package " + ii.packageName
12830 + " does not have a signature matching the target "
12831 + ii.targetPackage;
12832 reportStartInstrumentationFailure(watcher, className, msg);
12833 throw new SecurityException(msg);
12834 }
12835
12836 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012837 // Instrumentation can kill and relaunch even persistent processes
12838 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012839 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012840 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012841 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842 app.instrumentationProfileFile = profileFile;
12843 app.instrumentationArguments = arguments;
12844 app.instrumentationWatcher = watcher;
12845 app.instrumentationResultClass = className;
12846 Binder.restoreCallingIdentity(origId);
12847 }
12848
12849 return true;
12850 }
12851
12852 /**
12853 * Report errors that occur while attempting to start Instrumentation. Always writes the
12854 * error to the logs, but if somebody is watching, send the report there too. This enables
12855 * the "am" command to report errors with more information.
12856 *
12857 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12858 * @param cn The component name of the instrumentation.
12859 * @param report The error report.
12860 */
12861 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12862 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012863 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 try {
12865 if (watcher != null) {
12866 Bundle results = new Bundle();
12867 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12868 results.putString("Error", report);
12869 watcher.instrumentationStatus(cn, -1, results);
12870 }
12871 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012872 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012873 }
12874 }
12875
12876 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12877 if (app.instrumentationWatcher != null) {
12878 try {
12879 // NOTE: IInstrumentationWatcher *must* be oneway here
12880 app.instrumentationWatcher.instrumentationFinished(
12881 app.instrumentationClass,
12882 resultCode,
12883 results);
12884 } catch (RemoteException e) {
12885 }
12886 }
12887 app.instrumentationWatcher = null;
12888 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012889 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012890 app.instrumentationProfileFile = null;
12891 app.instrumentationArguments = null;
12892
Christopher Tate3dacd842011-08-19 14:56:15 -070012893 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012894 }
12895
12896 public void finishInstrumentation(IApplicationThread target,
12897 int resultCode, Bundle results) {
12898 // Refuse possible leaked file descriptors
12899 if (results != null && results.hasFileDescriptors()) {
12900 throw new IllegalArgumentException("File descriptors passed in Intent");
12901 }
12902
12903 synchronized(this) {
12904 ProcessRecord app = getRecordForAppLocked(target);
12905 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012906 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012907 return;
12908 }
12909 final long origId = Binder.clearCallingIdentity();
12910 finishInstrumentationLocked(app, resultCode, results);
12911 Binder.restoreCallingIdentity(origId);
12912 }
12913 }
12914
12915 // =========================================================
12916 // CONFIGURATION
12917 // =========================================================
12918
12919 public ConfigurationInfo getDeviceConfigurationInfo() {
12920 ConfigurationInfo config = new ConfigurationInfo();
12921 synchronized (this) {
12922 config.reqTouchScreen = mConfiguration.touchscreen;
12923 config.reqKeyboardType = mConfiguration.keyboard;
12924 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012925 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12926 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12928 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012929 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12930 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12932 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012933 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012934 }
12935 return config;
12936 }
12937
12938 public Configuration getConfiguration() {
12939 Configuration ci;
12940 synchronized(this) {
12941 ci = new Configuration(mConfiguration);
12942 }
12943 return ci;
12944 }
12945
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012946 public void updatePersistentConfiguration(Configuration values) {
12947 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12948 "updateConfiguration()");
12949 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12950 "updateConfiguration()");
12951 if (values == null) {
12952 throw new NullPointerException("Configuration must not be null");
12953 }
12954
12955 synchronized(this) {
12956 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012957 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012958 Binder.restoreCallingIdentity(origId);
12959 }
12960 }
12961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 public void updateConfiguration(Configuration values) {
12963 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12964 "updateConfiguration()");
12965
12966 synchronized(this) {
12967 if (values == null && mWindowManager != null) {
12968 // sentinel: fetch the current configuration from the window manager
12969 values = mWindowManager.computeNewConfiguration();
12970 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012971
12972 if (mWindowManager != null) {
12973 mProcessList.applyDisplaySize(mWindowManager);
12974 }
12975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012976 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012977 if (values != null) {
12978 Settings.System.clearConfiguration(values);
12979 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012980 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012981 Binder.restoreCallingIdentity(origId);
12982 }
12983 }
12984
12985 /**
12986 * Do either or both things: (1) change the current configuration, and (2)
12987 * make sure the given activity is running with the (now) current
12988 * configuration. Returns true if the activity has been left running, or
12989 * false if <var>starting</var> is being destroyed to match the new
12990 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012991 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012992 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012993 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012994 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012995 // do nothing if we are headless
12996 if (mHeadless) return true;
12997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998 int changes = 0;
12999
13000 boolean kept = true;
13001
13002 if (values != null) {
13003 Configuration newConfig = new Configuration(mConfiguration);
13004 changes = newConfig.updateFrom(values);
13005 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013006 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013007 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013008 }
13009
Doug Zongker2bec3d42009-12-04 12:52:44 -080013010 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013011
Dianne Hackborn813075a62011-11-14 17:45:19 -080013012 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013013 saveLocaleLocked(values.locale,
13014 !values.locale.equals(mConfiguration.locale),
13015 values.userSetLocale);
13016 }
13017
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013018 mConfigurationSeq++;
13019 if (mConfigurationSeq <= 0) {
13020 mConfigurationSeq = 1;
13021 }
13022 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013023 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013024 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013025
13026 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013027
13028 // TODO: If our config changes, should we auto dismiss any currently
13029 // showing dialogs?
13030 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013031
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013032 AttributeCache ac = AttributeCache.instance();
13033 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013034 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013036
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013037 // Make sure all resources in our process are updated
13038 // right now, so that anyone who is going to retrieve
13039 // resource values after we return will be sure to get
13040 // the new ones. This is especially important during
13041 // boot, where the first config change needs to guarantee
13042 // all resources have that config before following boot
13043 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013044 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013045
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013046 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013047 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013048 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013049 mHandler.sendMessage(msg);
13050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013052 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13053 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 try {
13055 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013056 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013057 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013058 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013059 }
13060 } catch (Exception e) {
13061 }
13062 }
13063 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013064 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13065 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013066 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013067 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013068 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13069 broadcastIntentLocked(null, null,
13070 new Intent(Intent.ACTION_LOCALE_CHANGED),
13071 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013072 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013074 }
13075 }
13076
13077 if (changes != 0 && starting == null) {
13078 // If the configuration changed, and the caller is not already
13079 // in the process of starting an activity, then find the top
13080 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013081 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082 }
13083
13084 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013085 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013086 // And we need to make sure at this point that all other activities
13087 // are made visible with the correct configuration.
13088 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013089 }
13090
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013091 if (values != null && mWindowManager != null) {
13092 mWindowManager.setNewConfiguration(mConfiguration);
13093 }
13094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013095 return kept;
13096 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013097
13098 /**
13099 * Decide based on the configuration whether we should shouw the ANR,
13100 * crash, etc dialogs. The idea is that if there is no affordnace to
13101 * press the on-screen buttons, we shouldn't show the dialog.
13102 *
13103 * A thought: SystemUI might also want to get told about this, the Power
13104 * dialog / global actions also might want different behaviors.
13105 */
13106 private static final boolean shouldShowDialogs(Configuration config) {
13107 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13108 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110
13111 /**
13112 * Save the locale. You must be inside a synchronized (this) block.
13113 */
13114 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13115 if(isDiff) {
13116 SystemProperties.set("user.language", l.getLanguage());
13117 SystemProperties.set("user.region", l.getCountry());
13118 }
13119
13120 if(isPersist) {
13121 SystemProperties.set("persist.sys.language", l.getLanguage());
13122 SystemProperties.set("persist.sys.country", l.getCountry());
13123 SystemProperties.set("persist.sys.localevar", l.getVariant());
13124 }
13125 }
13126
13127 // =========================================================
13128 // LIFETIME MANAGEMENT
13129 // =========================================================
13130
Christopher Tatef46723b2012-01-26 14:19:24 -080013131 // Returns which broadcast queue the app is the current [or imminent] receiver
13132 // on, or 'null' if the app is not an active broadcast recipient.
13133 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13134 BroadcastRecord r = app.curReceiver;
13135 if (r != null) {
13136 return r.queue;
13137 }
13138
13139 // It's not the current receiver, but it might be starting up to become one
13140 synchronized (this) {
13141 for (BroadcastQueue queue : mBroadcastQueues) {
13142 r = queue.mPendingBroadcast;
13143 if (r != null && r.curApp == app) {
13144 // found it; report which queue it's in
13145 return queue;
13146 }
13147 }
13148 }
13149
13150 return null;
13151 }
13152
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013153 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013154 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013155 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013156 // This adjustment has already been computed. If we are calling
13157 // from the top, we may have already computed our adjustment with
13158 // an earlier hidden adjustment that isn't really for us... if
13159 // so, use the new hidden adjustment.
13160 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013161 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013162 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013163 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164 }
13165
13166 if (app.thread == null) {
13167 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013168 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013169 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013170 }
13171
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013172 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13173 app.adjSource = null;
13174 app.adjTarget = null;
13175 app.empty = false;
13176 app.hidden = false;
13177
13178 final int activitiesSize = app.activities.size();
13179
Dianne Hackborn7d608422011-08-07 16:24:18 -070013180 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013181 // The max adjustment doesn't allow this app to be anything
13182 // below foreground, so it is not worth doing work for it.
13183 app.adjType = "fixed";
13184 app.adjSeq = mAdjSeq;
13185 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013186 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013187 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013188 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013189 // System process can do UI, and when they do we want to have
13190 // them trim their memory after the user leaves the UI. To
13191 // facilitate this, here we need to determine whether or not it
13192 // is currently showing UI.
13193 app.systemNoUi = true;
13194 if (app == TOP_APP) {
13195 app.systemNoUi = false;
13196 } else if (activitiesSize > 0) {
13197 for (int j = 0; j < activitiesSize; j++) {
13198 final ActivityRecord r = app.activities.get(j);
13199 if (r.visible) {
13200 app.systemNoUi = false;
13201 break;
13202 }
13203 }
13204 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013205 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013206 }
13207
13208 final boolean hadForegroundActivities = app.foregroundActivities;
13209
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013210 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013211 app.keeping = false;
13212 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213
The Android Open Source Project4df24232009-03-05 14:34:35 -080013214 // Determine the importance of the process, starting with most
13215 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013216 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013217 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013218 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013219 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013221 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013222 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013223 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013224 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013225 } else if (app.instrumentationClass != null) {
13226 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013227 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013228 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013229 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013230 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013231 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013232 // counts as being in the foreground for OOM killer purposes.
13233 // It's placed in a sched group based on the nature of the
13234 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013235 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013236 schedGroup = (queue == mFgBroadcastQueue)
13237 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013238 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013239 } else if (app.executingServices.size() > 0) {
13240 // An app that is currently executing a service callback also
13241 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013242 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013243 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013244 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013245 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013246 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013247 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013249 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013250 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013251 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013253 // A very not-needed process. If this is lower in the lru list,
13254 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013255 adj = hiddenAdj;
13256 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013257 app.hidden = true;
13258 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013259 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013260 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013261
13262 // Examine all activities if not already foreground.
13263 if (!app.foregroundActivities && activitiesSize > 0) {
13264 for (int j = 0; j < activitiesSize; j++) {
13265 final ActivityRecord r = app.activities.get(j);
13266 if (r.visible) {
13267 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013268 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13269 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013270 app.adjType = "visible";
13271 }
13272 schedGroup = Process.THREAD_GROUP_DEFAULT;
13273 app.hidden = false;
13274 app.foregroundActivities = true;
13275 break;
13276 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13277 || r.state == ActivityState.STOPPING) {
13278 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013279 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13280 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013281 app.adjType = "stopping";
13282 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013283 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013284 app.foregroundActivities = true;
13285 }
13286 }
13287 }
13288
Dianne Hackborn7d608422011-08-07 16:24:18 -070013289 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013290 if (app.foregroundServices) {
13291 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013292 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013293 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013294 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013295 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013296 } else if (app.forcingToForeground != null) {
13297 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013298 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013299 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013300 app.adjType = "force-foreground";
13301 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013302 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013303 }
13304 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013305
Dianne Hackborn7d608422011-08-07 16:24:18 -070013306 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013307 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013308 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013309 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013310 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013311 app.adjType = "heavy";
13312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013313
Dianne Hackborn7d608422011-08-07 16:24:18 -070013314 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013315 // This process is hosting what we currently consider to be the
13316 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013317 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013318 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013319 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013320 app.adjType = "home";
13321 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013322
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013323 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13324 && app.activities.size() > 0) {
13325 // This was the previous process that showed UI to the user.
13326 // We want to try to keep it around more aggressively, to give
13327 // a good experience around switching between two apps.
13328 adj = ProcessList.PREVIOUS_APP_ADJ;
13329 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13330 app.hidden = false;
13331 app.adjType = "previous";
13332 }
13333
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013334 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13335 + " reason=" + app.adjType);
13336
The Android Open Source Project4df24232009-03-05 14:34:35 -080013337 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 // there are applications dependent on our services or providers, but
13339 // this gives us a baseline and makes sure we don't get into an
13340 // infinite recursion.
13341 app.adjSeq = mAdjSeq;
13342 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013343
Christopher Tate6fa95972009-06-05 18:43:55 -070013344 if (mBackupTarget != null && app == mBackupTarget.app) {
13345 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013346 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013347 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013348 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013349 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013350 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013351 }
13352 }
13353
Dianne Hackborn7d608422011-08-07 16:24:18 -070013354 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013355 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013356 final long now = SystemClock.uptimeMillis();
13357 // This process is more important if the top activity is
13358 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013359 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013360 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013361 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013362 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013363 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013364 // If this process has shown some UI, let it immediately
13365 // go to the LRU list because it may be pretty heavy with
13366 // UI stuff. We'll tag it with a label just to help
13367 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013368 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013369 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013370 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013371 } else {
13372 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13373 // This service has seen some activity within
13374 // recent memory, so we will keep its process ahead
13375 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013376 if (adj > ProcessList.SERVICE_ADJ) {
13377 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013378 app.adjType = "started-services";
13379 app.hidden = false;
13380 }
13381 }
13382 // If we have let the service slide into the background
13383 // state, still have some text describing what it is doing
13384 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013385 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013386 app.adjType = "started-bg-services";
13387 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013388 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013389 // Don't kill this process because it is doing work; it
13390 // has said it is doing work.
13391 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013392 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013393 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013394 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013395 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013396 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013397 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013398 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013399 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013400 // XXX should compute this based on the max of
13401 // all connected clients.
13402 ConnectionRecord cr = clist.get(i);
13403 if (cr.binding.client == app) {
13404 // Binding to ourself is not interesting.
13405 continue;
13406 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013407 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013408 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013409 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013410 int myHiddenAdj = hiddenAdj;
13411 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013412 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013413 myHiddenAdj = client.hiddenAdj;
13414 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013415 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013416 }
13417 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013418 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013419 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013420 String adjType = null;
13421 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13422 // Not doing bind OOM management, so treat
13423 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013424 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013425 // If this process has shown some UI, let it immediately
13426 // go to the LRU list because it may be pretty heavy with
13427 // UI stuff. We'll tag it with a label just to help
13428 // debug and understand what is going on.
13429 if (adj > clientAdj) {
13430 adjType = "bound-bg-ui-services";
13431 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013432 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013433 clientAdj = adj;
13434 } else {
13435 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13436 // This service has not seen activity within
13437 // recent memory, so allow it to drop to the
13438 // LRU list if there is no other reason to keep
13439 // it around. We'll also tag it with a label just
13440 // to help debug and undertand what is going on.
13441 if (adj > clientAdj) {
13442 adjType = "bound-bg-services";
13443 }
13444 clientAdj = adj;
13445 }
13446 }
13447 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013448 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013449 // If this process has recently shown UI, and
13450 // the process that is binding to it is less
13451 // important than being visible, then we don't
13452 // care about the binding as much as we care
13453 // about letting this process get into the LRU
13454 // list to be killed and restarted if needed for
13455 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013456 if (app.hasShownUi && app != mHomeProcess
13457 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013458 adjType = "bound-bg-ui-services";
13459 } else {
13460 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13461 |Context.BIND_IMPORTANT)) != 0) {
13462 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013463 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13464 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13465 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13466 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13467 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013468 adj = clientAdj;
13469 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013470 app.pendingUiClean = true;
13471 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13472 adj = ProcessList.VISIBLE_APP_ADJ;
13473 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013474 }
13475 if (!client.hidden) {
13476 app.hidden = false;
13477 }
13478 if (client.keeping) {
13479 app.keeping = true;
13480 }
13481 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013482 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013483 }
13484 if (adjType != null) {
13485 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013486 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13487 .REASON_SERVICE_IN_USE;
13488 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013489 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013490 app.adjTarget = s.name;
13491 }
13492 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13493 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13494 schedGroup = Process.THREAD_GROUP_DEFAULT;
13495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496 }
13497 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013498 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13499 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013500 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013501 (a.visible || a.state == ActivityState.RESUMED
13502 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013503 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013504 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13505 schedGroup = Process.THREAD_GROUP_DEFAULT;
13506 }
13507 app.hidden = false;
13508 app.adjType = "service";
13509 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13510 .REASON_SERVICE_IN_USE;
13511 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013512 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013513 app.adjTarget = s.name;
13514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516 }
13517 }
13518 }
13519 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013520
Dianne Hackborn287952c2010-09-22 22:34:31 -070013521 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013522 // would like to avoid killing it unless it would prevent the current
13523 // application from running. By default we put the process in
13524 // with the rest of the background processes; as we scan through
13525 // its services we may bump it up from there.
13526 if (adj > hiddenAdj) {
13527 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013528 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013529 app.adjType = "bg-services";
13530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013531 }
13532
Dianne Hackborn7d608422011-08-07 16:24:18 -070013533 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013534 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013535 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013536 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013537 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013538 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013539 if (cpr.clients.size() != 0) {
13540 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013541 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013542 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013543 if (client == app) {
13544 // Being our own client is not interesting.
13545 continue;
13546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547 int myHiddenAdj = hiddenAdj;
13548 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013549 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013550 myHiddenAdj = client.hiddenAdj;
13551 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013552 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 }
13554 }
13555 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013556 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013557 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013558 if (app.hasShownUi && app != mHomeProcess
13559 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013560 app.adjType = "bg-ui-provider";
13561 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013562 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13563 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013564 app.adjType = "provider";
13565 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013566 if (!client.hidden) {
13567 app.hidden = false;
13568 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013569 if (client.keeping) {
13570 app.keeping = true;
13571 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013572 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13573 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013574 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013575 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013576 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013577 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013578 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13579 schedGroup = Process.THREAD_GROUP_DEFAULT;
13580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013581 }
13582 }
13583 // If the provider has external (non-framework) process
13584 // dependencies, ensure that its adjustment is at least
13585 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013586 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013587 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13588 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013589 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013590 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013591 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013592 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013593 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013594 }
13595 }
13596 }
13597 }
13598
13599 app.curRawAdj = adj;
13600
Joe Onorato8a9b2202010-02-26 18:56:32 -080013601 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013602 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13603 if (adj > app.maxAdj) {
13604 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013605 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013606 schedGroup = Process.THREAD_GROUP_DEFAULT;
13607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013609 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013610 app.keeping = true;
13611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013613 if (app.hasAboveClient) {
13614 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13615 // then we need to drop its adjustment to be lower than the service's
13616 // in order to honor the request. We want to drop it by one adjustment
13617 // level... but there is special meaning applied to various levels so
13618 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013619 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013620 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013621 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13622 adj = ProcessList.VISIBLE_APP_ADJ;
13623 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13624 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13625 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13626 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013627 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013628 adj++;
13629 }
13630 }
13631
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013632 if (adj == ProcessList.SERVICE_ADJ) {
13633 if (doingAll) {
13634 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13635 mNewNumServiceProcs++;
13636 }
13637 if (app.serviceb) {
13638 adj = ProcessList.SERVICE_B_ADJ;
13639 }
13640 } else {
13641 app.serviceb = false;
13642 }
13643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013644 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013645 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013646
13647 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013648 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13649 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013650 }
13651
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013652 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013653 }
13654
13655 /**
13656 * Ask a given process to GC right now.
13657 */
13658 final void performAppGcLocked(ProcessRecord app) {
13659 try {
13660 app.lastRequestedGc = SystemClock.uptimeMillis();
13661 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013662 if (app.reportLowMemory) {
13663 app.reportLowMemory = false;
13664 app.thread.scheduleLowMemory();
13665 } else {
13666 app.thread.processInBackground();
13667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013668 }
13669 } catch (Exception e) {
13670 // whatever.
13671 }
13672 }
13673
13674 /**
13675 * Returns true if things are idle enough to perform GCs.
13676 */
Josh Bartel7f208742010-02-25 11:01:44 -060013677 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013678 boolean processingBroadcasts = false;
13679 for (BroadcastQueue q : mBroadcastQueues) {
13680 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13681 processingBroadcasts = true;
13682 }
13683 }
13684 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013685 && (mSleeping || (mMainStack.mResumedActivity != null &&
13686 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 }
13688
13689 /**
13690 * Perform GCs on all processes that are waiting for it, but only
13691 * if things are idle.
13692 */
13693 final void performAppGcsLocked() {
13694 final int N = mProcessesToGc.size();
13695 if (N <= 0) {
13696 return;
13697 }
Josh Bartel7f208742010-02-25 11:01:44 -060013698 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013699 while (mProcessesToGc.size() > 0) {
13700 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013701 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013702 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13703 <= SystemClock.uptimeMillis()) {
13704 // To avoid spamming the system, we will GC processes one
13705 // at a time, waiting a few seconds between each.
13706 performAppGcLocked(proc);
13707 scheduleAppGcsLocked();
13708 return;
13709 } else {
13710 // It hasn't been long enough since we last GCed this
13711 // process... put it in the list to wait for its time.
13712 addProcessToGcListLocked(proc);
13713 break;
13714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013715 }
13716 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013717
13718 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013719 }
13720 }
13721
13722 /**
13723 * If all looks good, perform GCs on all processes waiting for them.
13724 */
13725 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013726 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013727 performAppGcsLocked();
13728 return;
13729 }
13730 // Still not idle, wait some more.
13731 scheduleAppGcsLocked();
13732 }
13733
13734 /**
13735 * Schedule the execution of all pending app GCs.
13736 */
13737 final void scheduleAppGcsLocked() {
13738 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013739
13740 if (mProcessesToGc.size() > 0) {
13741 // Schedule a GC for the time to the next process.
13742 ProcessRecord proc = mProcessesToGc.get(0);
13743 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13744
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013745 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013746 long now = SystemClock.uptimeMillis();
13747 if (when < (now+GC_TIMEOUT)) {
13748 when = now + GC_TIMEOUT;
13749 }
13750 mHandler.sendMessageAtTime(msg, when);
13751 }
13752 }
13753
13754 /**
13755 * Add a process to the array of processes waiting to be GCed. Keeps the
13756 * list in sorted order by the last GC time. The process can't already be
13757 * on the list.
13758 */
13759 final void addProcessToGcListLocked(ProcessRecord proc) {
13760 boolean added = false;
13761 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13762 if (mProcessesToGc.get(i).lastRequestedGc <
13763 proc.lastRequestedGc) {
13764 added = true;
13765 mProcessesToGc.add(i+1, proc);
13766 break;
13767 }
13768 }
13769 if (!added) {
13770 mProcessesToGc.add(0, proc);
13771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013772 }
13773
13774 /**
13775 * Set up to ask a process to GC itself. This will either do it
13776 * immediately, or put it on the list of processes to gc the next
13777 * time things are idle.
13778 */
13779 final void scheduleAppGcLocked(ProcessRecord app) {
13780 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013781 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013782 return;
13783 }
13784 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013785 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013786 scheduleAppGcsLocked();
13787 }
13788 }
13789
Dianne Hackborn287952c2010-09-22 22:34:31 -070013790 final void checkExcessivePowerUsageLocked(boolean doKills) {
13791 updateCpuStatsNow();
13792
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013793 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013794 boolean doWakeKills = doKills;
13795 boolean doCpuKills = doKills;
13796 if (mLastPowerCheckRealtime == 0) {
13797 doWakeKills = false;
13798 }
13799 if (mLastPowerCheckUptime == 0) {
13800 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013801 }
13802 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013803 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013804 }
13805 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013806 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13807 final long curUptime = SystemClock.uptimeMillis();
13808 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13809 mLastPowerCheckRealtime = curRealtime;
13810 mLastPowerCheckUptime = curUptime;
13811 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13812 doWakeKills = false;
13813 }
13814 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13815 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013816 }
13817 int i = mLruProcesses.size();
13818 while (i > 0) {
13819 i--;
13820 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013821 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013822 long wtime;
13823 synchronized (stats) {
13824 wtime = stats.getProcessWakeTime(app.info.uid,
13825 app.pid, curRealtime);
13826 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013827 long wtimeUsed = wtime - app.lastWakeTime;
13828 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13829 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013830 StringBuilder sb = new StringBuilder(128);
13831 sb.append("Wake for ");
13832 app.toShortString(sb);
13833 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013834 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013835 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013836 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013837 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013838 sb.append((wtimeUsed*100)/realtimeSince);
13839 sb.append("%)");
13840 Slog.i(TAG, sb.toString());
13841 sb.setLength(0);
13842 sb.append("CPU for ");
13843 app.toShortString(sb);
13844 sb.append(": over ");
13845 TimeUtils.formatDuration(uptimeSince, sb);
13846 sb.append(" used ");
13847 TimeUtils.formatDuration(cputimeUsed, sb);
13848 sb.append(" (");
13849 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013850 sb.append("%)");
13851 Slog.i(TAG, sb.toString());
13852 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013853 // If a process has held a wake lock for more
13854 // than 50% of the time during this period,
13855 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013856 if (doWakeKills && realtimeSince > 0
13857 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13858 synchronized (stats) {
13859 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13860 realtimeSince, wtimeUsed);
13861 }
13862 Slog.w(TAG, "Excessive wake lock in " + app.processName
13863 + " (pid " + app.pid + "): held " + wtimeUsed
13864 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013865 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13866 app.processName, app.setAdj, "excessive wake lock");
13867 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013868 } else if (doCpuKills && uptimeSince > 0
13869 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13870 synchronized (stats) {
13871 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13872 uptimeSince, cputimeUsed);
13873 }
13874 Slog.w(TAG, "Excessive CPU in " + app.processName
13875 + " (pid " + app.pid + "): used " + cputimeUsed
13876 + " during " + uptimeSince);
13877 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13878 app.processName, app.setAdj, "excessive cpu");
13879 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013880 } else {
13881 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013882 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013883 }
13884 }
13885 }
13886 }
13887
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013888 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013889 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 app.hiddenAdj = hiddenAdj;
13891
13892 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013893 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013894 }
13895
Dianne Hackborn287952c2010-09-22 22:34:31 -070013896 final boolean wasKeeping = app.keeping;
13897
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013898 boolean success = true;
13899
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013900 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013901
Jeff Brown10e89712011-07-08 18:52:57 -070013902 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013903 if (false) {
13904 // Removing for now. Forcing GCs is not so useful anymore
13905 // with Dalvik, and the new memory level hint facility is
13906 // better for what we need to do these days.
13907 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13908 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13909 // If this app is transitioning from foreground to
13910 // non-foreground, have it do a gc.
13911 scheduleAppGcLocked(app);
13912 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13913 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13914 // Likewise do a gc when an app is moving in to the
13915 // background (such as a service stopping).
13916 scheduleAppGcLocked(app);
13917 }
Jeff Brown10e89712011-07-08 18:52:57 -070013918 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013919
Jeff Brown10e89712011-07-08 18:52:57 -070013920 if (wasKeeping && !app.keeping) {
13921 // This app is no longer something we want to keep. Note
13922 // its current wake lock time to later know to kill it if
13923 // it is not behaving well.
13924 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13925 synchronized (stats) {
13926 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13927 app.pid, SystemClock.elapsedRealtime());
13928 }
13929 app.lastCpuTime = app.curCpuTime;
13930 }
13931
13932 app.setRawAdj = app.curRawAdj;
13933 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013934
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013935 if (app.curAdj != app.setAdj) {
13936 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013937 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013938 TAG, "Set " + app.pid + " " + app.processName +
13939 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013940 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013941 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013942 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013943 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013944 }
13945 }
13946 if (app.setSchedGroup != app.curSchedGroup) {
13947 app.setSchedGroup = app.curSchedGroup;
13948 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13949 "Setting process group of " + app.processName
13950 + " to " + app.curSchedGroup);
13951 if (app.waitingToKill != null &&
13952 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13953 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13954 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13955 app.processName, app.setAdj, app.waitingToKill);
13956 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013957 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013958 } else {
13959 if (true) {
13960 long oldId = Binder.clearCallingIdentity();
13961 try {
13962 Process.setProcessGroup(app.pid, app.curSchedGroup);
13963 } catch (Exception e) {
13964 Slog.w(TAG, "Failed setting process group of " + app.pid
13965 + " to " + app.curSchedGroup);
13966 e.printStackTrace();
13967 } finally {
13968 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013969 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013970 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013971 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013972 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013973 app.thread.setSchedulingGroup(app.curSchedGroup);
13974 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013975 }
13976 }
13977 }
13978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013979 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013980 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013981 }
13982
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013983 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013984 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013985 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013986 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013987 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013988 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013989 }
13990 }
13991 return resumedActivity;
13992 }
13993
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013994 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013995 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013996 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13997 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013998 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13999 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014000
14001 mAdjSeq++;
14002
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014003 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014004 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14005 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014006 if (nowHidden != wasHidden) {
14007 // Changed to/from hidden state, so apps after it in the LRU
14008 // list may also be changed.
14009 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014010 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014011 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014012 }
14013
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014014 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014015 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014016 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14017
14018 if (false) {
14019 RuntimeException e = new RuntimeException();
14020 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014021 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014022 }
14023
14024 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014025 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014026
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014027 // Let's determine how many processes we have running vs.
14028 // how many slots we have for background processes; we may want
14029 // to put multiple processes in a slot of there are enough of
14030 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014031 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014032 int factor = (mLruProcesses.size()-4)/numSlots;
14033 if (factor < 1) factor = 1;
14034 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014035 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014036
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014037 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014038 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014039 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014040 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014041 while (i > 0) {
14042 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014043 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014044 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014045 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14046 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014047 && app.curAdj == curHiddenAdj) {
14048 step++;
14049 if (step >= factor) {
14050 step = 0;
14051 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014052 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014053 }
14054 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014055 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014056 numHidden++;
14057 if (numHidden > mProcessLimit) {
14058 Slog.i(TAG, "No longer want " + app.processName
14059 + " (pid " + app.pid + "): hidden #" + numHidden);
14060 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14061 app.processName, app.setAdj, "too many background");
14062 app.killedBackground = true;
14063 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014064 }
14065 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014066 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14067 // If this is an isolated process, and there are no
14068 // services running in it, then the process is no longer
14069 // needed. We agressively kill these because we can by
14070 // definition not re-use the same process again, and it is
14071 // good to avoid having whatever code was running in them
14072 // left sitting around after no longer needed.
14073 Slog.i(TAG, "Isolated process " + app.processName
14074 + " (pid " + app.pid + ") no longer needed");
14075 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14076 app.processName, app.setAdj, "isolated not needed");
14077 app.killedBackground = true;
14078 Process.killProcessQuiet(app.pid);
14079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014080 }
14081 }
14082
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014083 mNumServiceProcs = mNewNumServiceProcs;
14084
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014085 // Now determine the memory trimming level of background processes.
14086 // Unfortunately we need to start at the back of the list to do this
14087 // properly. We only do this if the number of background apps we
14088 // are managing to keep around is less than half the maximum we desire;
14089 // if we are keeping a good number around, we'll let them use whatever
14090 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014091 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014092 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014093 factor = numHidden/3;
14094 int minFactor = 2;
14095 if (mHomeProcess != null) minFactor++;
14096 if (mPreviousProcess != null) minFactor++;
14097 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014098 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014099 int fgTrimLevel;
14100 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14101 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14102 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14103 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14104 } else {
14105 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14106 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014107 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014108 for (i=0; i<N; i++) {
14109 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014110 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14111 && app.curAdj != ProcessList.SERVICE_B_ADJ
14112 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014113 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14114 try {
14115 app.thread.scheduleTrimMemory(curLevel);
14116 } catch (RemoteException e) {
14117 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014118 if (false) {
14119 // For now we won't do this; our memory trimming seems
14120 // to be good enough at this point that destroying
14121 // activities causes more harm than good.
14122 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14123 && app != mHomeProcess && app != mPreviousProcess) {
14124 // For these apps we will also finish their activities
14125 // to help them free memory.
14126 mMainStack.destroyActivitiesLocked(app, false, "trim");
14127 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014128 }
14129 }
14130 app.trimMemoryLevel = curLevel;
14131 step++;
14132 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014133 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014134 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014135 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14136 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014137 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014138 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14139 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014140 break;
14141 }
14142 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014143 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014144 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014145 && app.thread != null) {
14146 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014147 app.thread.scheduleTrimMemory(
14148 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014149 } catch (RemoteException e) {
14150 }
14151 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014152 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014153 } else {
14154 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14155 && app.pendingUiClean) {
14156 // If this application is now in the background and it
14157 // had done UI, then give it the special trim level to
14158 // have it free UI resources.
14159 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14160 if (app.trimMemoryLevel < level && app.thread != null) {
14161 try {
14162 app.thread.scheduleTrimMemory(level);
14163 } catch (RemoteException e) {
14164 }
14165 }
14166 app.pendingUiClean = false;
14167 }
14168 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014169 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014170 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014171 } catch (RemoteException e) {
14172 }
14173 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014174 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014175 }
14176 }
14177 } else {
14178 final int N = mLruProcesses.size();
14179 for (i=0; i<N; i++) {
14180 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014181 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014182 && app.pendingUiClean) {
14183 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14184 && app.thread != null) {
14185 try {
14186 app.thread.scheduleTrimMemory(
14187 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14188 } catch (RemoteException e) {
14189 }
14190 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014191 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014192 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014193 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014194 }
14195 }
14196
14197 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014198 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014200 }
14201
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014202 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014203 synchronized (this) {
14204 int i;
14205
14206 // First remove any unused application processes whose package
14207 // has been removed.
14208 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14209 final ProcessRecord app = mRemovedProcesses.get(i);
14210 if (app.activities.size() == 0
14211 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014212 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014213 TAG, "Exiting empty application process "
14214 + app.processName + " ("
14215 + (app.thread != null ? app.thread.asBinder() : null)
14216 + ")\n");
14217 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014218 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14219 app.processName, app.setAdj, "empty");
14220 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014221 } else {
14222 try {
14223 app.thread.scheduleExit();
14224 } catch (Exception e) {
14225 // Ignore exceptions.
14226 }
14227 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014228 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014229 mRemovedProcesses.remove(i);
14230
14231 if (app.persistent) {
14232 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014233 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014234 }
14235 }
14236 }
14237 }
14238
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014239 // Now update the oom adj for all processes.
14240 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014241 }
14242 }
14243
14244 /** This method sends the specified signal to each of the persistent apps */
14245 public void signalPersistentProcesses(int sig) throws RemoteException {
14246 if (sig != Process.SIGNAL_USR1) {
14247 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14248 }
14249
14250 synchronized (this) {
14251 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14252 != PackageManager.PERMISSION_GRANTED) {
14253 throw new SecurityException("Requires permission "
14254 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14255 }
14256
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014257 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14258 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014259 if (r.thread != null && r.persistent) {
14260 Process.sendSignal(r.pid, sig);
14261 }
14262 }
14263 }
14264 }
14265
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014266 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14267 if (proc == null || proc == mProfileProc) {
14268 proc = mProfileProc;
14269 path = mProfileFile;
14270 profileType = mProfileType;
14271 clearProfilerLocked();
14272 }
14273 if (proc == null) {
14274 return;
14275 }
14276 try {
14277 proc.thread.profilerControl(false, path, null, profileType);
14278 } catch (RemoteException e) {
14279 throw new IllegalStateException("Process disappeared");
14280 }
14281 }
14282
14283 private void clearProfilerLocked() {
14284 if (mProfileFd != null) {
14285 try {
14286 mProfileFd.close();
14287 } catch (IOException e) {
14288 }
14289 }
14290 mProfileApp = null;
14291 mProfileProc = null;
14292 mProfileFile = null;
14293 mProfileType = 0;
14294 mAutoStopProfiler = false;
14295 }
14296
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014297 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014298 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014299
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014300 try {
14301 synchronized (this) {
14302 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14303 // its own permission.
14304 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14305 != PackageManager.PERMISSION_GRANTED) {
14306 throw new SecurityException("Requires permission "
14307 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014308 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014309
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014310 if (start && fd == null) {
14311 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014312 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014313
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014314 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014315 if (process != null) {
14316 try {
14317 int pid = Integer.parseInt(process);
14318 synchronized (mPidsSelfLocked) {
14319 proc = mPidsSelfLocked.get(pid);
14320 }
14321 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014322 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014323
14324 if (proc == null) {
14325 HashMap<String, SparseArray<ProcessRecord>> all
14326 = mProcessNames.getMap();
14327 SparseArray<ProcessRecord> procs = all.get(process);
14328 if (procs != null && procs.size() > 0) {
14329 proc = procs.valueAt(0);
14330 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014331 }
14332 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014333
14334 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014335 throw new IllegalArgumentException("Unknown process: " + process);
14336 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014337
14338 if (start) {
14339 stopProfilerLocked(null, null, 0);
14340 setProfileApp(proc.info, proc.processName, path, fd, false);
14341 mProfileProc = proc;
14342 mProfileType = profileType;
14343 try {
14344 fd = fd.dup();
14345 } catch (IOException e) {
14346 fd = null;
14347 }
14348 proc.thread.profilerControl(start, path, fd, profileType);
14349 fd = null;
14350 mProfileFd = null;
14351 } else {
14352 stopProfilerLocked(proc, path, profileType);
14353 if (fd != null) {
14354 try {
14355 fd.close();
14356 } catch (IOException e) {
14357 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014358 }
14359 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014360
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014361 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014362 }
14363 } catch (RemoteException e) {
14364 throw new IllegalStateException("Process disappeared");
14365 } finally {
14366 if (fd != null) {
14367 try {
14368 fd.close();
14369 } catch (IOException e) {
14370 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014371 }
14372 }
14373 }
Andy McFadden824c5102010-07-09 16:26:57 -070014374
14375 public boolean dumpHeap(String process, boolean managed,
14376 String path, ParcelFileDescriptor fd) throws RemoteException {
14377
14378 try {
14379 synchronized (this) {
14380 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14381 // its own permission (same as profileControl).
14382 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14383 != PackageManager.PERMISSION_GRANTED) {
14384 throw new SecurityException("Requires permission "
14385 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14386 }
14387
14388 if (fd == null) {
14389 throw new IllegalArgumentException("null fd");
14390 }
14391
14392 ProcessRecord proc = null;
14393 try {
14394 int pid = Integer.parseInt(process);
14395 synchronized (mPidsSelfLocked) {
14396 proc = mPidsSelfLocked.get(pid);
14397 }
14398 } catch (NumberFormatException e) {
14399 }
14400
14401 if (proc == null) {
14402 HashMap<String, SparseArray<ProcessRecord>> all
14403 = mProcessNames.getMap();
14404 SparseArray<ProcessRecord> procs = all.get(process);
14405 if (procs != null && procs.size() > 0) {
14406 proc = procs.valueAt(0);
14407 }
14408 }
14409
14410 if (proc == null || proc.thread == null) {
14411 throw new IllegalArgumentException("Unknown process: " + process);
14412 }
14413
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014414 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14415 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014416 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14417 throw new SecurityException("Process not debuggable: " + proc);
14418 }
14419 }
14420
14421 proc.thread.dumpHeap(managed, path, fd);
14422 fd = null;
14423 return true;
14424 }
14425 } catch (RemoteException e) {
14426 throw new IllegalStateException("Process disappeared");
14427 } finally {
14428 if (fd != null) {
14429 try {
14430 fd.close();
14431 } catch (IOException e) {
14432 }
14433 }
14434 }
14435 }
14436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014437 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14438 public void monitor() {
14439 synchronized (this) { }
14440 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014441
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014442 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014443 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14444 ProcessRecord processRecord = mLruProcesses.get(i);
14445 try {
14446 if (processRecord.thread != null) {
14447 processRecord.thread.setCoreSettings(settings);
14448 }
14449 } catch (RemoteException re) {
14450 /* ignore */
14451 }
14452 }
14453 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014454
14455 // Multi-user methods
14456
Amith Yamasani742a6712011-05-04 14:49:28 -070014457 private int mCurrentUserId;
14458 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014459 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14460
14461 public interface UserListener {
14462 public void onUserChanged(int userId);
14463
14464 public void onUserAdded(int userId);
14465
14466 public void onUserRemoved(int userId);
14467
14468 public void onUserLoggedOut(int userId);
14469 }
14470
14471 public void addUserListener(UserListener listener) {
14472 synchronized (this) {
14473 if (!mUserListeners.contains(listener)) {
14474 mUserListeners.add(listener);
14475 }
14476 }
14477 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014478
14479 public boolean switchUser(int userId) {
14480 final int callingUid = Binder.getCallingUid();
14481 if (callingUid != 0 && callingUid != Process.myUid()) {
14482 Slog.e(TAG, "Trying to switch user from unauthorized app");
14483 return false;
14484 }
14485 if (mCurrentUserId == userId)
14486 return true;
14487
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014488 ArrayList<UserListener> listeners;
14489
Amith Yamasani742a6712011-05-04 14:49:28 -070014490 synchronized (this) {
14491 // Check if user is already logged in, otherwise check if user exists first before
14492 // adding to the list of logged in users.
14493 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14494 if (!userExists(userId)) {
14495 return false;
14496 }
14497 mLoggedInUsers.append(userId, userId);
14498 }
14499
14500 mCurrentUserId = userId;
14501 boolean haveActivities = mMainStack.switchUser(userId);
14502 if (!haveActivities) {
14503 startHomeActivityLocked(userId);
14504 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014505
14506 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14507 }
14508 // Inform the listeners
14509 for (UserListener listener : listeners) {
14510 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014511 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014512 return true;
14513 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014514
14515 private boolean userExists(int userId) {
14516 try {
14517 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14518 for (UserInfo user : users) {
14519 if (user.id == userId) {
14520 return true;
14521 }
14522 }
14523 } catch (RemoteException re) {
14524 // Won't happen, in same process
14525 }
14526
14527 return false;
14528 }
14529
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014530 private void checkValidCaller(int uid, int userId) {
14531 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14532
14533 throw new SecurityException("Caller uid=" + uid
14534 + " is not privileged to communicate with user=" + userId);
14535 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014536
14537 private int applyUserId(int uid, int userId) {
14538 return UserId.getUid(userId, uid);
14539 }
14540
14541 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014542 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014543 ApplicationInfo newInfo = new ApplicationInfo(info);
14544 newInfo.uid = applyUserId(info.uid, userId);
14545 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14546 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14547 + info.packageName;
14548 }
14549 return newInfo;
14550 }
14551
14552 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014553 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014554 || userId < 1) {
14555 return aInfo;
14556 }
14557
14558 ActivityInfo info = new ActivityInfo(aInfo);
14559 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14560 return info;
14561 }
14562
14563 static class ServiceMap {
14564
14565 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14566 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14567 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14568 mServicesByIntentPerUser = new SparseArray<
14569 HashMap<Intent.FilterComparison, ServiceRecord>>();
14570
14571 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14572 // TODO: Deal with global services
14573 if (DEBUG_MU)
14574 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14575 return getServices(callingUser).get(name);
14576 }
14577
14578 ServiceRecord getServiceByName(ComponentName name) {
14579 return getServiceByName(name, -1);
14580 }
14581
14582 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14583 // TODO: Deal with global services
14584 if (DEBUG_MU)
14585 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14586 return getServicesByIntent(callingUser).get(filter);
14587 }
14588
14589 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14590 return getServiceByIntent(filter, -1);
14591 }
14592
14593 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14594 // TODO: Deal with global services
14595 getServices(callingUser).put(name, value);
14596 }
14597
14598 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14599 ServiceRecord value) {
14600 // TODO: Deal with global services
14601 getServicesByIntent(callingUser).put(filter, value);
14602 }
14603
14604 void removeServiceByName(ComponentName name, int callingUser) {
14605 // TODO: Deal with global services
14606 ServiceRecord removed = getServices(callingUser).remove(name);
14607 if (DEBUG_MU)
14608 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14609 + " removed=" + removed);
14610 }
14611
14612 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14613 // TODO: Deal with global services
14614 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14615 if (DEBUG_MU)
14616 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14617 + " removed=" + removed);
14618 }
14619
14620 Collection<ServiceRecord> getAllServices(int callingUser) {
14621 // TODO: Deal with global services
14622 return getServices(callingUser).values();
14623 }
14624
14625 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14626 HashMap map = mServicesByNamePerUser.get(callingUser);
14627 if (map == null) {
14628 map = new HashMap<ComponentName, ServiceRecord>();
14629 mServicesByNamePerUser.put(callingUser, map);
14630 }
14631 return map;
14632 }
14633
14634 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14635 int callingUser) {
14636 HashMap map = mServicesByIntentPerUser.get(callingUser);
14637 if (map == null) {
14638 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14639 mServicesByIntentPerUser.put(callingUser, map);
14640 }
14641 return map;
14642 }
14643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014644}