blob: e37adc7ab2c38745df6daced45a08bd089d809b5 [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;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070065import android.content.IIntentReceiver;
66import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070067import android.content.Intent;
68import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070069import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ConfigurationInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageManager;
75import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080076import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070079import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.ProviderInfo;
81import android.content.pm.ResolveInfo;
82import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070083import android.content.pm.UserInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040084import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.res.Configuration;
86import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070087import android.net.Proxy;
88import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.net.Uri;
90import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080091import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070093import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080096import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.FileUtils;
98import android.os.Handler;
99import android.os.IBinder;
100import android.os.IPermissionController;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Parcel;
104import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700106import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.RemoteException;
108import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700109import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.SystemClock;
111import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700112import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700114import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700117import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700119import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700121import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700122import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.view.Gravity;
124import android.view.LayoutInflater;
125import android.view.View;
126import android.view.WindowManager;
127import android.view.WindowManagerPolicy;
128
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700129import java.io.BufferedInputStream;
130import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700131import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.DataInputStream;
133import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import java.io.File;
135import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200139import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800140import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700142import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.lang.ref.WeakReference;
144import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700145import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import java.util.Collections;
147import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Locale;
153import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700154import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700155import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700159public final class ActivityManagerService extends ActivityManagerNative
160 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400165 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_SWITCH = localLOGV || false;
167 static final boolean DEBUG_TASKS = localLOGV || false;
168 static final boolean DEBUG_PAUSE = localLOGV || false;
169 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
170 static final boolean DEBUG_TRANSITION = localLOGV || false;
171 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800172 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700173 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700175 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_VISBILITY = localLOGV || false;
177 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700178 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800179 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700182 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700183 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700184 static final boolean DEBUG_POWER = localLOGV || false;
185 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700186 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean VALIDATE_TOKENS = false;
188 static final boolean SHOW_ACTIVITY_START_TIME = true;
189
190 // Control over CPU and battery monitoring.
191 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
192 static final boolean MONITOR_CPU_USAGE = true;
193 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
194 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
195 static final boolean MONITOR_THREAD_CPU_USAGE = false;
196
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700198 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800200 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700202 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // Maximum number of recent tasks that we can remember.
205 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700206
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700207 // Amount of time after a call to stopAppSwitches() during which we will
208 // prevent further untrusted switches from happening.
209 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 // 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.
213 static final int PROC_START_TIMEOUT = 10*1000;
214
Jeff Brown3f9dd282011-07-08 20:02:19 -0700215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real, when the process was
217 // started with a wrapper for instrumentation (such as Valgrind) because it
218 // could take much longer than usual.
219 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // How long to wait after going idle before forcing apps to GC.
222 static final int GC_TIMEOUT = 5*1000;
223
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700224 // The minimum amount of time between successive GC requests for a process.
225 static final int GC_MIN_INTERVAL = 60*1000;
226
Dianne Hackborn287952c2010-09-22 22:34:31 -0700227 // The rate at which we check for apps using excessive power -- 15 mins.
228 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on wake locks to start killing things.
232 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on CPU usage to start killing things.
236 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800239 static final int BROADCAST_FG_TIMEOUT = 10*1000;
240 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // How long we wait for a service to finish executing.
243 static final int SERVICE_TIMEOUT = 20*1000;
244
245 // How long a service needs to be running until restarting its process
246 // is no longer considered to be a relaunch of the service.
247 static final int SERVICE_RESTART_DURATION = 5*1000;
248
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700249 // How long a service needs to be running until it will start back at
250 // SERVICE_RESTART_DURATION after being killed.
251 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
252
253 // Multiplying factor to increase restart duration time by, for each time
254 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
255 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
256
257 // The minimum amount of time between restarting services that we allow.
258 // That is, when multiple services are restarting, we won't allow each
259 // to restart less than this amount of time from the last one.
260 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 // Maximum amount of time for there to be no activity on a service before
263 // we consider it non-essential and allow its process to go on the
264 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700265 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // How long we wait until we timeout on key dispatching.
268 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // How long we wait until we timeout on key dispatching during instrumentation.
271 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
272
Dan Egnor42471dd2010-01-07 17:25:22 -0800273 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 static final String[] EMPTY_STRING_ARRAY = new String[0];
276
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700277 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700278
279 private final boolean mHeadless;
280
Joe Onorato54a4a412011-11-02 20:50:08 -0700281 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
282 // default actuion automatically. Important for devices without direct input
283 // devices.
284 private boolean mShowDialogs = true;
285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700287 * Description of a request to start a new activity, which has been held
288 * due to app switches being disabled.
289 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700290 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 ActivityRecord r;
292 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700293 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700294 }
295
296 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
297 = new ArrayList<PendingActivityLaunch>();
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 BroadcastQueue mFgBroadcastQueue;
301 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800302 // Convenient for easy iteration over the queues. Foreground is first
303 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800304 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800305
306 BroadcastQueue broadcastQueueForIntent(Intent intent) {
307 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
308 if (DEBUG_BACKGROUND_BROADCAST) {
309 Slog.i(TAG, "Broadcast intent " + intent + " on "
310 + (isFg ? "foreground" : "background")
311 + " queue");
312 }
313 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
314 }
315
316 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
317 for (BroadcastQueue queue : mBroadcastQueues) {
318 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
319 if (r != null) {
320 return r;
321 }
322 }
323 return null;
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * Activity we have told the window manager to have key focus.
328 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700329 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700330 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * List of intents that were used to start the most recent tasks.
332 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700333 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
335 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700336 * Process management.
337 */
338 final ProcessList mProcessList = new ProcessList();
339
340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * All of the applications we currently have running organized by name.
342 * The keys are strings of the application package name (as
343 * returned by the package manager), and the keys are ApplicationRecord
344 * objects.
345 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700346 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
348 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800349 * The currently running isolated processes.
350 */
351 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
352
353 /**
354 * Counter for assigning isolated process uids, to avoid frequently reusing the
355 * same ones.
356 */
357 int mNextIsolatedProcessUid = 0;
358
359 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700360 * The currently running heavy-weight process, if any.
361 */
362 ProcessRecord mHeavyWeightProcess = null;
363
364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 * The last time that various processes have crashed.
366 */
367 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
368
369 /**
370 * Set of applications that we consider to be bad, and will reject
371 * incoming broadcasts from (which the user has no control over).
372 * Processes are added to this set when they have crashed twice within
373 * a minimum amount of time; they are removed from it when they are
374 * later restarted (hopefully due to some user action). The value is the
375 * time it was added to the list.
376 */
377 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
378
379 /**
380 * All of the processes we currently have running organized by pid.
381 * The keys are the pid running the application.
382 *
383 * <p>NOTE: This object is protected by its own lock, NOT the global
384 * activity manager lock!
385 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388 /**
389 * All of the processes that have been forced to be foreground. The key
390 * is the pid of the caller who requested it (we hold a death
391 * link on it).
392 */
393 abstract class ForegroundToken implements IBinder.DeathRecipient {
394 int pid;
395 IBinder token;
396 }
397 final SparseArray<ForegroundToken> mForegroundProcesses
398 = new SparseArray<ForegroundToken>();
399
400 /**
401 * List of records for processes that someone had tried to start before the
402 * system was ready. We don't start them at that point, but ensure they
403 * are started by the time booting is complete.
404 */
405 final ArrayList<ProcessRecord> mProcessesOnHold
406 = new ArrayList<ProcessRecord>();
407
408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 * List of persistent applications that are in the process
410 * of being started.
411 */
412 final ArrayList<ProcessRecord> mPersistentStartingProcesses
413 = new ArrayList<ProcessRecord>();
414
415 /**
416 * Processes that are being forcibly torn down.
417 */
418 final ArrayList<ProcessRecord> mRemovedProcesses
419 = new ArrayList<ProcessRecord>();
420
421 /**
422 * List of running applications, sorted by recent usage.
423 * The first entry in the list is the least recently used.
424 * It contains ApplicationRecord objects. This list does NOT include
425 * any persistent application records (since we never want to exit them).
426 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800427 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 = new ArrayList<ProcessRecord>();
429
430 /**
431 * List of processes that should gc as soon as things are idle.
432 */
433 final ArrayList<ProcessRecord> mProcessesToGc
434 = new ArrayList<ProcessRecord>();
435
436 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437 * This is the process holding what we currently consider to be
438 * the "home" activity.
439 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800441
442 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700443 * This is the process holding the activity the user last visited that
444 * is in a different process from the one they are currently in.
445 */
446 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800447
448 /**
449 * The time at which the previous process was last visible.
450 */
451 long mPreviousProcessVisibleTime;
452
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700453 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 * Packages that the user has asked to have run in screen size
455 * compatibility mode instead of filling the screen.
456 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700457 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458
459 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 * Set of PendingResultRecord objects that are currently active.
461 */
462 final HashSet mPendingResultRecords = new HashSet();
463
464 /**
465 * Set of IntentSenderRecord objects that are currently active.
466 */
467 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
468 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
469
470 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800471 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700472 * already logged DropBox entries for. Guarded by itself. If
473 * something (rogue user app) forces this over
474 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
475 */
476 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
477 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
478
479 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700480 * Strict Mode background batched logging state.
481 *
482 * The string buffer is guarded by itself, and its lock is also
483 * used to determine if another batched write is already
484 * in-flight.
485 */
486 private final StringBuilder mStrictModeBuffer = new StringBuilder();
487
488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 * Keeps track of all IIntentReceivers that have been registered for
490 * broadcasts. Hash keys are the receiver IBinder, hash value is
491 * a ReceiverList.
492 */
493 final HashMap mRegisteredReceivers = new HashMap();
494
495 /**
496 * Resolver for broadcast intents to registered receivers.
497 * Holds BroadcastFilter (subclass of IntentFilter).
498 */
499 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
500 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
501 @Override
502 protected boolean allowFilterResult(
503 BroadcastFilter filter, List<BroadcastFilter> dest) {
504 IBinder target = filter.receiverList.receiver.asBinder();
505 for (int i=dest.size()-1; i>=0; i--) {
506 if (dest.get(i).receiverList.receiver.asBinder() == target) {
507 return false;
508 }
509 }
510 return true;
511 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700512
513 @Override
514 protected String packageForFilter(BroadcastFilter filter) {
515 return filter.packageName;
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 };
518
519 /**
520 * State of all active sticky broadcasts. Keys are the action of the
521 * sticky Intent, values are an ArrayList of all broadcasted intents with
522 * that action (which should usually be one).
523 */
524 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
525 new HashMap<String, ArrayList<Intent>>();
526
Amith Yamasani742a6712011-05-04 14:49:28 -0700527 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528
529 /**
530 * All currently bound service connections. Keys are the IBinder of
531 * the client's IServiceConnection.
532 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700533 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
534 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 /**
537 * List of services that we have been asked to start,
538 * but haven't yet been able to. It is used to hold start requests
539 * while waiting for their corresponding application thread to get
540 * going.
541 */
542 final ArrayList<ServiceRecord> mPendingServices
543 = new ArrayList<ServiceRecord>();
544
545 /**
546 * List of services that are scheduled to restart following a crash.
547 */
548 final ArrayList<ServiceRecord> mRestartingServices
549 = new ArrayList<ServiceRecord>();
550
551 /**
552 * List of services that are in the process of being stopped.
553 */
554 final ArrayList<ServiceRecord> mStoppingServices
555 = new ArrayList<ServiceRecord>();
556
557 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 * Backup/restore process management
559 */
560 String mBackupAppName = null;
561 BackupRecord mBackupTarget = null;
562
563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * List of PendingThumbnailsRecord objects of clients who are still
565 * waiting to receive all of the thumbnails for a task.
566 */
567 final ArrayList mPendingThumbnails = new ArrayList();
568
569 /**
570 * List of HistoryRecord objects that have been finished and must
571 * still report back to a pending thumbnail receiver.
572 */
573 final ArrayList mCancelledThumbnails = new ArrayList();
574
Amith Yamasani742a6712011-05-04 14:49:28 -0700575 final ProviderMap mProviderMap = new ProviderMap();
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 /**
578 * List of content providers who have clients waiting for them. The
579 * application is currently being launched and the provider will be
580 * removed from this list once it is published.
581 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700582 final ArrayList<ContentProviderRecord> mLaunchingProviders
583 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 /**
586 * Global set of specific Uri permissions that have been granted.
587 */
588 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
589 = new SparseArray<HashMap<Uri, UriPermission>>();
590
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800591 CoreSettingsObserver mCoreSettingsObserver;
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
594 * Thread-local storage used to carry caller permissions over through
595 * indirect content-provider access.
596 * @see #ActivityManagerService.openContentUri()
597 */
598 private class Identity {
599 public int pid;
600 public int uid;
601
602 Identity(int _pid, int _uid) {
603 pid = _pid;
604 uid = _uid;
605 }
606 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
609
610 /**
611 * All information we have collected about the runtime performance of
612 * any user id that can impact battery performance.
613 */
614 final BatteryStatsService mBatteryStatsService;
615
616 /**
617 * information about component usage
618 */
619 final UsageStatsService mUsageStatsService;
620
621 /**
622 * Current configuration information. HistoryRecord objects are given
623 * a reference to this object to indicate which configuration they are
624 * currently running in, so this object must be kept immutable.
625 */
626 Configuration mConfiguration = new Configuration();
627
628 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800629 * Current sequencing integer of the configuration, for skipping old
630 * configurations.
631 */
632 int mConfigurationSeq = 0;
633
634 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700635 * Hardware-reported OpenGLES version.
636 */
637 final int GL_ES_VERSION;
638
639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * List of initialization arguments to pass to all processes when binding applications to them.
641 * For example, references to the commonly used services.
642 */
643 HashMap<String, IBinder> mAppBindArgs;
644
645 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700646 * Temporary to avoid allocations. Protected by main lock.
647 */
648 final StringBuilder mStringBuilder = new StringBuilder(256);
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * Used to control how we initialize the service.
652 */
653 boolean mStartRunning = false;
654 ComponentName mTopComponent;
655 String mTopAction;
656 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700657 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 boolean mSystemReady = false;
659 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700660 boolean mWaitingUpdate = false;
661 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700662 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700663 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
665 Context mContext;
666
667 int mFactoryTest;
668
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700669 boolean mCheckedForSetup;
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700672 * The time at which we will allow normal application switches again,
673 * after a call to {@link #stopAppSwitches()}.
674 */
675 long mAppSwitchesAllowedTime;
676
677 /**
678 * This is set to true after the first switch after mAppSwitchesAllowedTime
679 * is set; any switches after that will clear the time.
680 */
681 boolean mDidAppSwitch;
682
683 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 long mLastPowerCheckRealtime;
687
688 /**
689 * Last time (in uptime) at which we checked for power usage.
690 */
691 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * Set while we are wanting to sleep, to prevent any
695 * activities from being started/resumed.
696 */
697 boolean mSleeping = false;
698
699 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700700 * State of external calls telling us if the device is asleep.
701 */
702 boolean mWentToSleep = false;
703
704 /**
705 * State of external call telling us if the lock screen is shown.
706 */
707 boolean mLockScreenShown = false;
708
709 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700710 * Set if we are shutting down the system, similar to sleeping.
711 */
712 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
714 /**
715 * Task identifier that activities are currently being started
716 * in. Incremented each time a new task is created.
717 * todo: Replace this with a TokenSpace class that generates non-repeating
718 * integers that won't wrap.
719 */
720 int mCurTask = 1;
721
722 /**
723 * Current sequence id for oom_adj computation traversal.
724 */
725 int mAdjSeq = 0;
726
727 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700728 * Current sequence id for process LRU updating.
729 */
730 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
732 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700733 * Keep track of the number of service processes we last found, to
734 * determine on the next iteration which should be B services.
735 */
736 int mNumServiceProcs = 0;
737 int mNewNumServiceProcs = 0;
738
739 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 * System monitoring: number of processes that died since the last
741 * N procs were started.
742 */
743 int[] mProcDeaths = new int[20];
744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700745 /**
746 * This is set if we had to do a delayed dexopt of an app before launching
747 * it, to increasing the ANR timeouts in that case.
748 */
749 boolean mDidDexOpt;
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 String mDebugApp = null;
752 boolean mWaitForDebugger = false;
753 boolean mDebugTransient = false;
754 String mOrigDebugApp = null;
755 boolean mOrigWaitForDebugger = false;
756 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700757 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700758 String mProfileApp = null;
759 ProcessRecord mProfileProc = null;
760 String mProfileFile;
761 ParcelFileDescriptor mProfileFd;
762 int mProfileType = 0;
763 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800764 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
Jeff Sharkeya4620792011-05-20 15:29:23 -0700766 final RemoteCallbackList<IProcessObserver> mProcessObservers
767 = new RemoteCallbackList<IProcessObserver>();
768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 /**
770 * Callback of last caller to {@link #requestPss}.
771 */
772 Runnable mRequestPssCallback;
773
774 /**
775 * Remaining processes for which we are waiting results from the last
776 * call to {@link #requestPss}.
777 */
778 final ArrayList<ProcessRecord> mRequestPssList
779 = new ArrayList<ProcessRecord>();
780
781 /**
782 * Runtime statistics collection thread. This object's lock is used to
783 * protect all related state.
784 */
785 final Thread mProcessStatsThread;
786
787 /**
788 * Used to collect process stats when showing not responding dialog.
789 * Protected by mProcessStatsThread.
790 */
791 final ProcessStats mProcessStats = new ProcessStats(
792 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700793 final AtomicLong mLastCpuTime = new AtomicLong(0);
794 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 long mLastWriteTime = 0;
797
798 /**
799 * Set to true after the system has finished booting.
800 */
801 boolean mBooted = false;
802
Dianne Hackborn7d608422011-08-07 16:24:18 -0700803 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700804 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805
806 WindowManagerService mWindowManager;
807
808 static ActivityManagerService mSelf;
809 static ActivityThread mSystemThread;
810
811 private final class AppDeathRecipient implements IBinder.DeathRecipient {
812 final ProcessRecord mApp;
813 final int mPid;
814 final IApplicationThread mAppThread;
815
816 AppDeathRecipient(ProcessRecord app, int pid,
817 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 TAG, "New death recipient " + this
820 + " for thread " + thread.asBinder());
821 mApp = app;
822 mPid = pid;
823 mAppThread = thread;
824 }
825
826 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 TAG, "Death received in " + this
829 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 synchronized(ActivityManagerService.this) {
831 appDiedLocked(mApp, mPid, mAppThread);
832 }
833 }
834 }
835
836 static final int SHOW_ERROR_MSG = 1;
837 static final int SHOW_NOT_RESPONDING_MSG = 2;
838 static final int SHOW_FACTORY_ERROR_MSG = 3;
839 static final int UPDATE_CONFIGURATION_MSG = 4;
840 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
841 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 static final int SERVICE_TIMEOUT_MSG = 12;
843 static final int UPDATE_TIME_ZONE = 13;
844 static final int SHOW_UID_ERROR_MSG = 14;
845 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700847 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700848 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800849 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700850 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
851 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700852 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700853 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700854 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700855 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700856 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700857 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
858 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700859 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800861 static final int FIRST_ACTIVITY_STACK_MSG = 100;
862 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
863 static final int FIRST_COMPAT_MODE_MSG = 300;
864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700866 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700867 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868
869 final Handler mHandler = new Handler() {
870 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 //}
873
874 public void handleMessage(Message msg) {
875 switch (msg.what) {
876 case SHOW_ERROR_MSG: {
877 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 synchronized (ActivityManagerService.this) {
879 ProcessRecord proc = (ProcessRecord)data.get("app");
880 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 return;
883 }
884 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700885 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800886 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 d.show();
888 proc.crashDialog = d;
889 } else {
890 // The device is asleep, so just pretend that the user
891 // saw a crash dialog and hit "force quit".
892 res.set(0);
893 }
894 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700895
896 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } break;
898 case SHOW_NOT_RESPONDING_MSG: {
899 synchronized (ActivityManagerService.this) {
900 HashMap data = (HashMap) msg.obj;
901 ProcessRecord proc = (ProcessRecord)data.get("app");
902 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800903 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 return;
905 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700907 Intent intent = new Intent("android.intent.action.ANR");
908 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800909 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
910 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700911 }
912 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800913 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700914 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800915
Justin Kohbc52ca22012-03-29 15:11:44 -0700916 if (mShowDialogs) {
917 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700918 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700919 d.show();
920 proc.anrDialog = d;
921 } else {
922 // Just kill the app if there is no dialog to be shown.
923 killAppAtUsersRequest(proc, null);
924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700926
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700927 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700929 case SHOW_STRICT_MODE_VIOLATION_MSG: {
930 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
931 synchronized (ActivityManagerService.this) {
932 ProcessRecord proc = (ProcessRecord) data.get("app");
933 if (proc == null) {
934 Slog.e(TAG, "App not found when showing strict mode dialog.");
935 break;
936 }
937 if (proc.crashDialog != null) {
938 Slog.e(TAG, "App already has strict mode dialog: " + proc);
939 return;
940 }
941 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700942 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700943 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
944 d.show();
945 proc.crashDialog = d;
946 } else {
947 // The device is asleep, so just pretend that the user
948 // saw a crash dialog and hit "force quit".
949 res.set(0);
950 }
951 }
952 ensureBootCompleted();
953 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 case SHOW_FACTORY_ERROR_MSG: {
955 Dialog d = new FactoryErrorDialog(
956 mContext, msg.getData().getCharSequence("msg"));
957 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700958 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 } break;
960 case UPDATE_CONFIGURATION_MSG: {
961 final ContentResolver resolver = mContext.getContentResolver();
962 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
963 } break;
964 case GC_BACKGROUND_PROCESSES_MSG: {
965 synchronized (ActivityManagerService.this) {
966 performAppGcsIfAppropriateLocked();
967 }
968 } break;
969 case WAIT_FOR_DEBUGGER_MSG: {
970 synchronized (ActivityManagerService.this) {
971 ProcessRecord app = (ProcessRecord)msg.obj;
972 if (msg.arg1 != 0) {
973 if (!app.waitedForDebugger) {
974 Dialog d = new AppWaitingForDebuggerDialog(
975 ActivityManagerService.this,
976 mContext, app);
977 app.waitDialog = d;
978 app.waitedForDebugger = true;
979 d.show();
980 }
981 } else {
982 if (app.waitDialog != null) {
983 app.waitDialog.dismiss();
984 app.waitDialog = null;
985 }
986 }
987 }
988 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700990 if (mDidDexOpt) {
991 mDidDexOpt = false;
992 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
993 nmsg.obj = msg.obj;
994 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
995 return;
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 serviceTimeout((ProcessRecord)msg.obj);
998 } break;
999 case UPDATE_TIME_ZONE: {
1000 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (r.thread != null) {
1004 try {
1005 r.thread.updateTimeZone();
1006 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001007 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009 }
1010 }
1011 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001012 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001013 case CLEAR_DNS_CACHE: {
1014 synchronized (ActivityManagerService.this) {
1015 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1016 ProcessRecord r = mLruProcesses.get(i);
1017 if (r.thread != null) {
1018 try {
1019 r.thread.clearDnsCache();
1020 } catch (RemoteException ex) {
1021 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1022 }
1023 }
1024 }
1025 }
1026 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001027 case UPDATE_HTTP_PROXY: {
1028 ProxyProperties proxy = (ProxyProperties)msg.obj;
1029 String host = "";
1030 String port = "";
1031 String exclList = "";
1032 if (proxy != null) {
1033 host = proxy.getHost();
1034 port = Integer.toString(proxy.getPort());
1035 exclList = proxy.getExclusionList();
1036 }
1037 synchronized (ActivityManagerService.this) {
1038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
1040 if (r.thread != null) {
1041 try {
1042 r.thread.setHttpProxy(host, port, exclList);
1043 } catch (RemoteException ex) {
1044 Slog.w(TAG, "Failed to update http proxy for: " +
1045 r.info.processName);
1046 }
1047 }
1048 }
1049 }
1050 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001052 String title = "System UIDs Inconsistent";
1053 String text = "UIDs on the system are inconsistent, you need to wipe your"
1054 + " data partition or your device will be unstable.";
1055 Log.e(TAG, title + ": " + text);
1056 if (mShowDialogs) {
1057 // XXX This is a temporary dialog, no need to localize.
1058 AlertDialog d = new BaseErrorDialog(mContext);
1059 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1060 d.setCancelable(false);
1061 d.setTitle(title);
1062 d.setMessage(text);
1063 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1064 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1065 mUidAlert = d;
1066 d.show();
1067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } break;
1069 case IM_FEELING_LUCKY_MSG: {
1070 if (mUidAlert != null) {
1071 mUidAlert.dismiss();
1072 mUidAlert = null;
1073 }
1074 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001076 if (mDidDexOpt) {
1077 mDidDexOpt = false;
1078 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1079 nmsg.obj = msg.obj;
1080 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1081 return;
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 ProcessRecord app = (ProcessRecord)msg.obj;
1084 synchronized (ActivityManagerService.this) {
1085 processStartTimedOutLocked(app);
1086 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001087 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001088 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1089 synchronized (ActivityManagerService.this) {
1090 doPendingActivityLaunchesLocked(true);
1091 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001092 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001093 case KILL_APPLICATION_MSG: {
1094 synchronized (ActivityManagerService.this) {
1095 int uid = msg.arg1;
1096 boolean restart = (msg.arg2 == 1);
1097 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001098 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1099 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001100 }
1101 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001102 case FINALIZE_PENDING_INTENT_MSG: {
1103 ((PendingIntentRecord)msg.obj).completeFinalize();
1104 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001105 case POST_HEAVY_NOTIFICATION_MSG: {
1106 INotificationManager inm = NotificationManager.getService();
1107 if (inm == null) {
1108 return;
1109 }
1110
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001111 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001112 ProcessRecord process = root.app;
1113 if (process == null) {
1114 return;
1115 }
1116
1117 try {
1118 Context context = mContext.createPackageContext(process.info.packageName, 0);
1119 String text = mContext.getString(R.string.heavy_weight_notification,
1120 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1121 Notification notification = new Notification();
1122 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1123 notification.when = 0;
1124 notification.flags = Notification.FLAG_ONGOING_EVENT;
1125 notification.tickerText = text;
1126 notification.defaults = 0; // please be quiet
1127 notification.sound = null;
1128 notification.vibrate = null;
1129 notification.setLatestEventInfo(context, text,
1130 mContext.getText(R.string.heavy_weight_notification_detail),
1131 PendingIntent.getActivity(mContext, 0, root.intent,
1132 PendingIntent.FLAG_CANCEL_CURRENT));
1133
1134 try {
1135 int[] outId = new int[1];
1136 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1137 notification, outId);
1138 } catch (RuntimeException e) {
1139 Slog.w(ActivityManagerService.TAG,
1140 "Error showing notification for heavy-weight app", e);
1141 } catch (RemoteException e) {
1142 }
1143 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001144 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001145 }
1146 } break;
1147 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1148 INotificationManager inm = NotificationManager.getService();
1149 if (inm == null) {
1150 return;
1151 }
1152 try {
1153 inm.cancelNotification("android",
1154 R.string.heavy_weight_notification);
1155 } catch (RuntimeException e) {
1156 Slog.w(ActivityManagerService.TAG,
1157 "Error canceling notification for service", e);
1158 } catch (RemoteException e) {
1159 }
1160 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001161 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1162 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001163 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001164 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001165 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1166 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001167 }
1168 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001169 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1170 synchronized (ActivityManagerService.this) {
1171 ActivityRecord ar = (ActivityRecord)msg.obj;
1172 if (mCompatModeDialog != null) {
1173 if (mCompatModeDialog.mAppInfo.packageName.equals(
1174 ar.info.applicationInfo.packageName)) {
1175 return;
1176 }
1177 mCompatModeDialog.dismiss();
1178 mCompatModeDialog = null;
1179 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001180 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001181 if (mCompatModePackages.getPackageAskCompatModeLocked(
1182 ar.packageName)) {
1183 int mode = mCompatModePackages.computeCompatModeLocked(
1184 ar.info.applicationInfo);
1185 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1186 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1187 mCompatModeDialog = new CompatModeDialog(
1188 ActivityManagerService.this, mContext,
1189 ar.info.applicationInfo);
1190 mCompatModeDialog.show();
1191 }
1192 }
1193 }
1194 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001195 break;
1196 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001197 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001198 final int pid = msg.arg1;
1199 final int uid = msg.arg2;
1200 final boolean foregroundActivities = (Boolean) msg.obj;
1201 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001202 break;
1203 }
1204 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001205 final int pid = msg.arg1;
1206 final int uid = msg.arg2;
1207 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001208 break;
1209 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001210 case REPORT_MEM_USAGE: {
1211 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1212 if (!isDebuggable) {
1213 return;
1214 }
1215 synchronized (ActivityManagerService.this) {
1216 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001217 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1218 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001219 // avoid spamming.
1220 return;
1221 }
1222 mLastMemUsageReportTime = now;
1223 }
1224 Thread thread = new Thread() {
1225 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001226 StringBuilder dropBuilder = new StringBuilder(1024);
1227 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001228 StringWriter oomSw = new StringWriter();
1229 PrintWriter oomPw = new PrintWriter(oomSw);
1230 StringWriter catSw = new StringWriter();
1231 PrintWriter catPw = new PrintWriter(catSw);
1232 String[] emptyArgs = new String[] { };
1233 StringBuilder tag = new StringBuilder(128);
1234 StringBuilder stack = new StringBuilder(128);
1235 tag.append("Low on memory -- ");
1236 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1237 tag, stack);
1238 dropBuilder.append(stack);
1239 dropBuilder.append('\n');
1240 dropBuilder.append('\n');
1241 String oomString = oomSw.toString();
1242 dropBuilder.append(oomString);
1243 dropBuilder.append('\n');
1244 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 try {
1246 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1247 "procrank", });
1248 final InputStreamReader converter = new InputStreamReader(
1249 proc.getInputStream());
1250 BufferedReader in = new BufferedReader(converter);
1251 String line;
1252 while (true) {
1253 line = in.readLine();
1254 if (line == null) {
1255 break;
1256 }
1257 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 logBuilder.append(line);
1259 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(line);
1262 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 }
1264 converter.close();
1265 } catch (IOException e) {
1266 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001267 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001271 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001272 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001273 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001274 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001275 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001276 addErrorToDropBox("lowmem", null, "system_server", null,
1277 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001278 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001279 synchronized (ActivityManagerService.this) {
1280 long now = SystemClock.uptimeMillis();
1281 if (mLastMemUsageReportTime < now) {
1282 mLastMemUsageReportTime = now;
1283 }
1284 }
1285 }
1286 };
1287 thread.start();
1288 break;
1289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291 }
1292 };
1293
1294 public static void setSystemProcess() {
1295 try {
1296 ActivityManagerService m = mSelf;
1297
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001298 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001300 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001301 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (MONITOR_CPU_USAGE) {
1303 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 ServiceManager.addService("permission", new PermissionController(m));
1306
1307 ApplicationInfo info =
1308 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001309 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001310 mSystemThread.installSystemApplicationInfo(info);
1311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 synchronized (mSelf) {
1313 ProcessRecord app = mSelf.newProcessRecordLocked(
1314 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001315 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001317 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001318 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001319 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 synchronized (mSelf.mPidsSelfLocked) {
1321 mSelf.mPidsSelfLocked.put(app.pid, app);
1322 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001323 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325 } catch (PackageManager.NameNotFoundException e) {
1326 throw new RuntimeException(
1327 "Unable to find android system package", e);
1328 }
1329 }
1330
1331 public void setWindowManager(WindowManagerService wm) {
1332 mWindowManager = wm;
1333 }
1334
1335 public static final Context main(int factoryTest) {
1336 AThread thr = new AThread();
1337 thr.start();
1338
1339 synchronized (thr) {
1340 while (thr.mService == null) {
1341 try {
1342 thr.wait();
1343 } catch (InterruptedException e) {
1344 }
1345 }
1346 }
1347
1348 ActivityManagerService m = thr.mService;
1349 mSelf = m;
1350 ActivityThread at = ActivityThread.systemMain();
1351 mSystemThread = at;
1352 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001353 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 m.mContext = context;
1355 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001356 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 m.mBatteryStatsService.publish(context);
1359 m.mUsageStatsService.publish(context);
1360
1361 synchronized (thr) {
1362 thr.mReady = true;
1363 thr.notifyAll();
1364 }
1365
1366 m.startRunning(null, null, null, null);
1367
1368 return context;
1369 }
1370
1371 public static ActivityManagerService self() {
1372 return mSelf;
1373 }
1374
1375 static class AThread extends Thread {
1376 ActivityManagerService mService;
1377 boolean mReady = false;
1378
1379 public AThread() {
1380 super("ActivityManager");
1381 }
1382
1383 public void run() {
1384 Looper.prepare();
1385
1386 android.os.Process.setThreadPriority(
1387 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001388 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389
1390 ActivityManagerService m = new ActivityManagerService();
1391
1392 synchronized (this) {
1393 mService = m;
1394 notifyAll();
1395 }
1396
1397 synchronized (this) {
1398 while (!mReady) {
1399 try {
1400 wait();
1401 } catch (InterruptedException e) {
1402 }
1403 }
1404 }
1405
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001406 // For debug builds, log event loop stalls to dropbox for analysis.
1407 if (StrictMode.conditionallyEnableDebugLogging()) {
1408 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 Looper.loop();
1412 }
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 static class MemBinder extends Binder {
1416 ActivityManagerService mActivityManagerService;
1417 MemBinder(ActivityManagerService activityManagerService) {
1418 mActivityManagerService = activityManagerService;
1419 }
1420
1421 @Override
1422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001423 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1424 != PackageManager.PERMISSION_GRANTED) {
1425 pw.println("Permission Denial: can't dump meminfo from from pid="
1426 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1427 + " without permission " + android.Manifest.permission.DUMP);
1428 return;
1429 }
1430
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001431 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001432 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434 }
1435
Chet Haase9c1e23b2011-03-24 10:51:31 -07001436 static class GraphicsBinder extends Binder {
1437 ActivityManagerService mActivityManagerService;
1438 GraphicsBinder(ActivityManagerService activityManagerService) {
1439 mActivityManagerService = activityManagerService;
1440 }
1441
1442 @Override
1443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001444 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1445 != PackageManager.PERMISSION_GRANTED) {
1446 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1447 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1448 + " without permission " + android.Manifest.permission.DUMP);
1449 return;
1450 }
1451
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001452 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001453 }
1454 }
1455
Jeff Brown6754ba22011-12-14 20:20:01 -08001456 static class DbBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 DbBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump dbinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
1472 mActivityManagerService.dumpDbInfo(fd, pw, args);
1473 }
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 static class CpuBinder extends Binder {
1477 ActivityManagerService mActivityManagerService;
1478 CpuBinder(ActivityManagerService activityManagerService) {
1479 mActivityManagerService = activityManagerService;
1480 }
1481
1482 @Override
1483 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001484 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1485 != PackageManager.PERMISSION_GRANTED) {
1486 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1487 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1488 + " without permission " + android.Manifest.permission.DUMP);
1489 return;
1490 }
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001493 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1494 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1495 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497 }
1498 }
1499
1500 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001502
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001503 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1504 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1505 mBroadcastQueues[0] = mFgBroadcastQueue;
1506 mBroadcastQueues[1] = mBgBroadcastQueue;
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 File dataDir = Environment.getDataDirectory();
1509 File systemDir = new File(dataDir, "system");
1510 systemDir.mkdirs();
1511 mBatteryStatsService = new BatteryStatsService(new File(
1512 systemDir, "batterystats.bin").toString());
1513 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001514 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001515 mOnBattery = DEBUG_POWER ? true
1516 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001517 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001519 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001520 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001521 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Jack Palevichb90d28c2009-07-22 15:35:24 -07001523 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1524 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1525
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001526 mConfiguration.setToDefaults();
1527 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001528 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 mProcessStats.init();
1530
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001531 mCompatModePackages = new CompatModePackages(this, systemDir);
1532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 // Add ourself to the Watchdog monitors.
1534 Watchdog.getInstance().addMonitor(this);
1535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 mProcessStatsThread = new Thread("ProcessStats") {
1537 public void run() {
1538 while (true) {
1539 try {
1540 try {
1541 synchronized(this) {
1542 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001543 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // + ", write delay=" + nextWriteDelay);
1547 if (nextWriteDelay < nextCpuDelay) {
1548 nextCpuDelay = nextWriteDelay;
1549 }
1550 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001551 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 this.wait(nextCpuDelay);
1553 }
1554 }
1555 } catch (InterruptedException e) {
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 updateCpuStatsNow();
1558 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001559 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561 }
1562 }
1563 };
1564 mProcessStatsThread.start();
1565 }
1566
1567 @Override
1568 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1569 throws RemoteException {
1570 try {
1571 return super.onTransact(code, data, reply, flags);
1572 } catch (RuntimeException e) {
1573 // The activity manager only throws security exceptions, so let's
1574 // log all others.
1575 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001576 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 throw e;
1579 }
1580 }
1581
1582 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001583 final long now = SystemClock.uptimeMillis();
1584 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1585 return;
1586 }
1587 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1588 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 mProcessStatsThread.notify();
1590 }
1591 }
1592 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 void updateCpuStatsNow() {
1595 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001596 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 final long now = SystemClock.uptimeMillis();
1598 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001601 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1602 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 haveNewCpuStats = true;
1604 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 //Slog.i(TAG, mProcessStats.printCurrentState());
1606 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 // + mProcessStats.getTotalCpuPercent() + "%");
1608
Joe Onorato8a9b2202010-02-26 18:56:32 -08001609 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 if ("true".equals(SystemProperties.get("events.cpu"))) {
1611 int user = mProcessStats.getLastUserTime();
1612 int system = mProcessStats.getLastSystemTime();
1613 int iowait = mProcessStats.getLastIoWaitTime();
1614 int irq = mProcessStats.getLastIrqTime();
1615 int softIrq = mProcessStats.getLastSoftIrqTime();
1616 int idle = mProcessStats.getLastIdleTime();
1617
1618 int total = user + system + iowait + irq + softIrq + idle;
1619 if (total == 0) total = 1;
1620
Doug Zongker2bec3d42009-12-04 12:52:44 -08001621 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 ((user+system+iowait+irq+softIrq) * 100) / total,
1623 (user * 100) / total,
1624 (system * 100) / total,
1625 (iowait * 100) / total,
1626 (irq * 100) / total,
1627 (softIrq * 100) / total);
1628 }
1629 }
1630
Amith Yamasanie43530a2009-08-21 13:11:37 -07001631 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001632 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001633 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 synchronized(mPidsSelfLocked) {
1635 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001636 if (mOnBattery) {
1637 int perc = bstats.startAddingCpuLocked();
1638 int totalUTime = 0;
1639 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001640 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001642 ProcessStats.Stats st = mProcessStats.getStats(i);
1643 if (!st.working) {
1644 continue;
1645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001647 int otherUTime = (st.rel_utime*perc)/100;
1648 int otherSTime = (st.rel_stime*perc)/100;
1649 totalUTime += otherUTime;
1650 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (pr != null) {
1652 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001653 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1654 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001655 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001656 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001657 } else {
1658 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001659 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001660 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1662 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001663 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001667 bstats.finishAddingCpuLocked(perc, totalUTime,
1668 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670 }
1671 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1674 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001675 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677 }
1678 }
1679 }
1680
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001681 @Override
1682 public void batteryNeedsCpuUpdate() {
1683 updateCpuStatsNow();
1684 }
1685
1686 @Override
1687 public void batteryPowerChanged(boolean onBattery) {
1688 // When plugging in, update the CPU stats first before changing
1689 // the plug state.
1690 updateCpuStatsNow();
1691 synchronized (this) {
1692 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001693 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001694 }
1695 }
1696 }
1697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 /**
1699 * Initialize the application bind args. These are passed to each
1700 * process when the bindApplication() IPC is sent to the process. They're
1701 * lazily setup to make sure the services are running when they're asked for.
1702 */
1703 private HashMap<String, IBinder> getCommonServicesLocked() {
1704 if (mAppBindArgs == null) {
1705 mAppBindArgs = new HashMap<String, IBinder>();
1706
1707 // Setup the application init args
1708 mAppBindArgs.put("package", ServiceManager.getService("package"));
1709 mAppBindArgs.put("window", ServiceManager.getService("window"));
1710 mAppBindArgs.put(Context.ALARM_SERVICE,
1711 ServiceManager.getService(Context.ALARM_SERVICE));
1712 }
1713 return mAppBindArgs;
1714 }
1715
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001716 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (mFocusedActivity != r) {
1718 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001719 if (r != null) {
1720 mWindowManager.setFocusedApp(r.appToken, true);
1721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723 }
1724
Dianne Hackborn906497c2010-05-10 15:57:38 -07001725 private final void updateLruProcessInternalLocked(ProcessRecord app,
1726 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001728 int lrui = mLruProcesses.indexOf(app);
1729 if (lrui >= 0) mLruProcesses.remove(lrui);
1730
1731 int i = mLruProcesses.size()-1;
1732 int skipTop = 0;
1733
Dianne Hackborn906497c2010-05-10 15:57:38 -07001734 app.lruSeq = mLruSeq;
1735
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 // compute the new weight for this process.
1737 if (updateActivityTime) {
1738 app.lastActivityTime = SystemClock.uptimeMillis();
1739 }
1740 if (app.activities.size() > 0) {
1741 // If this process has activities, we more strongly want to keep
1742 // it around.
1743 app.lruWeight = app.lastActivityTime;
1744 } else if (app.pubProviders.size() > 0) {
1745 // If this process contains content providers, we want to keep
1746 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001747 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001748 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001749 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001750 } else {
1751 // If this process doesn't have activities, we less strongly
1752 // want to keep it around, and generally want to avoid getting
1753 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001754 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001755 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001756 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001758
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001759 while (i >= 0) {
1760 ProcessRecord p = mLruProcesses.get(i);
1761 // If this app shouldn't be in front of the first N background
1762 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001763 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001764 skipTop--;
1765 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001766 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 mLruProcesses.add(i+1, app);
1768 break;
1769 }
1770 i--;
1771 }
1772 if (i < 0) {
1773 mLruProcesses.add(0, app);
1774 }
1775
Dianne Hackborn906497c2010-05-10 15:57:38 -07001776 // If the app is currently using a content provider or service,
1777 // bump those processes as well.
1778 if (app.connections.size() > 0) {
1779 for (ConnectionRecord cr : app.connections) {
1780 if (cr.binding != null && cr.binding.service != null
1781 && cr.binding.service.app != null
1782 && cr.binding.service.app.lruSeq != mLruSeq) {
1783 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1784 updateActivityTime, i+1);
1785 }
1786 }
1787 }
1788 if (app.conProviders.size() > 0) {
1789 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001790 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1791 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001792 updateActivityTime, i+1);
1793 }
1794 }
1795 }
1796
Joe Onorato8a9b2202010-02-26 18:56:32 -08001797 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 if (oomAdj) {
1799 updateOomAdjLocked();
1800 }
1801 }
1802
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001804 boolean oomAdj, boolean updateActivityTime) {
1805 mLruSeq++;
1806 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1807 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 String processName, int uid) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001811 // Temporary hack to make Settings run per user
1812 if (uid == Process.SYSTEM_UID && !processName.equals("com.android.settings")) {
1813 // The system gets to run in any process. If there are multiple
1814 // processes with the same uid, just pick the first (this
1815 // should never happen).
1816 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1817 processName);
1818 return procs != null ? procs.valueAt(0) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001820 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 ProcessRecord proc = mProcessNames.get(processName, uid);
1822 return proc;
1823 }
1824
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001825 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001826 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001827 try {
1828 if (pm.performDexOpt(packageName)) {
1829 mDidDexOpt = true;
1830 }
1831 } catch (RemoteException e) {
1832 }
1833 }
1834
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001835 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 int transit = mWindowManager.getPendingAppTransition();
1837 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1838 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1839 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1840 }
1841
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001842 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001844 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1845 boolean isolated) {
1846 ProcessRecord app;
1847 if (!isolated) {
1848 app = getProcessRecordLocked(processName, info.uid);
1849 } else {
1850 // If this is an isolated process, it can't re-use an existing process.
1851 app = null;
1852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 // We don't have to do anything more if:
1854 // (1) There is an existing application record; and
1855 // (2) The caller doesn't think it is dead, OR there is no thread
1856 // object attached to it so we know it couldn't have crashed; and
1857 // (3) There is a pid assigned to it, so it is either starting or
1858 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001859 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 + " app=" + app + " knownToBeDead=" + knownToBeDead
1861 + " thread=" + (app != null ? app.thread : null)
1862 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001863 if (app != null && app.pid > 0) {
1864 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001865 // We already have the app running, or are waiting for it to
1866 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001867 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001868 // If this is a new package in the process, add the package to the list
1869 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001870 return app;
1871 } else {
1872 // An application record is attached to a previous process,
1873 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001874 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001875 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 String hostingNameStr = hostingName != null
1880 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001881
1882 if (!isolated) {
1883 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1884 // If we are in the background, then check to see if this process
1885 // is bad. If so, we will just silently fail.
1886 if (mBadProcesses.get(info.processName, info.uid) != null) {
1887 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1888 + "/" + info.processName);
1889 return null;
1890 }
1891 } else {
1892 // When the user is explicitly starting a process, then clear its
1893 // crash count so that we won't make it bad until they see at
1894 // least one crash dialog again, and make the process good again
1895 // if it had been bad.
1896 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001897 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001898 mProcessCrashTimes.remove(info.processName, info.uid);
1899 if (mBadProcesses.get(info.processName, info.uid) != null) {
1900 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1901 info.processName);
1902 mBadProcesses.remove(info.processName, info.uid);
1903 if (app != null) {
1904 app.bad = false;
1905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907 }
1908 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001911 app = newProcessRecordLocked(null, info, processName, isolated);
1912 if (app == null) {
1913 Slog.w(TAG, "Failed making new process record for "
1914 + processName + "/" + info.uid + " isolated=" + isolated);
1915 return null;
1916 }
1917 mProcessNames.put(processName, app.uid, app);
1918 if (isolated) {
1919 mIsolatedProcesses.put(app.uid, app);
1920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 } else {
1922 // If this is a new package in the process, add the package to the list
1923 app.addPackage(info.packageName);
1924 }
1925
1926 // If the system is not ready yet, then hold off on starting this
1927 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001928 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001929 && !isAllowedWhileBooting(info)
1930 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 if (!mProcessesOnHold.contains(app)) {
1932 mProcessesOnHold.add(app);
1933 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001934 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 return app;
1936 }
1937
1938 startProcessLocked(app, hostingType, hostingNameStr);
1939 return (app.pid != 0) ? app : null;
1940 }
1941
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001942 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1943 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1944 }
1945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 private final void startProcessLocked(ProcessRecord app,
1947 String hostingType, String hostingNameStr) {
1948 if (app.pid > 0 && app.pid != MY_PID) {
1949 synchronized (mPidsSelfLocked) {
1950 mPidsSelfLocked.remove(app.pid);
1951 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1952 }
1953 app.pid = 0;
1954 }
1955
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001956 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1957 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 mProcessesOnHold.remove(app);
1959
1960 updateCpuStats();
1961
1962 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1963 mProcDeaths[0] = 0;
1964
1965 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001966 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001969 if (!app.isolated) {
1970 try {
1971 gids = mContext.getPackageManager().getPackageGids(
1972 app.info.packageName);
1973 } catch (PackageManager.NameNotFoundException e) {
1974 Slog.w(TAG, "Unable to retrieve gids", e);
1975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1978 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1979 && mTopComponent != null
1980 && app.processName.equals(mTopComponent.getPackageName())) {
1981 uid = 0;
1982 }
1983 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1984 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1985 uid = 0;
1986 }
1987 }
1988 int debugFlags = 0;
1989 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1990 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001991 // Also turn on CheckJNI for debuggable apps. It's quite
1992 // awkward to turn on otherwise.
1993 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001995 // Run the app in safe mode if its manifest requests so or the
1996 // system is booted in safe mode.
1997 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1998 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001999 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2002 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2003 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002004 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2005 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 if ("1".equals(SystemProperties.get("debug.assert"))) {
2008 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2009 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002010
2011 // Start the process. It will either succeed and return a result containing
2012 // the PID of the new process, or else throw a RuntimeException.
2013 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002014 app.processName, uid, uid, gids, debugFlags,
2015 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2018 synchronized (bs) {
2019 if (bs.isOnBattery()) {
2020 app.batteryStats.incStartsLocked();
2021 }
2022 }
2023
Jeff Brown3f9dd282011-07-08 20:02:19 -07002024 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 app.processName, hostingType,
2026 hostingNameStr != null ? hostingNameStr : "");
2027
2028 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002029 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002032 StringBuilder buf = mStringBuilder;
2033 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 buf.append("Start proc ");
2035 buf.append(app.processName);
2036 buf.append(" for ");
2037 buf.append(hostingType);
2038 if (hostingNameStr != null) {
2039 buf.append(" ");
2040 buf.append(hostingNameStr);
2041 }
2042 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002043 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 buf.append(" uid=");
2045 buf.append(uid);
2046 buf.append(" gids={");
2047 if (gids != null) {
2048 for (int gi=0; gi<gids.length; gi++) {
2049 if (gi != 0) buf.append(", ");
2050 buf.append(gids[gi]);
2051
2052 }
2053 }
2054 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002055 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002056 app.pid = startResult.pid;
2057 app.usingWrapper = startResult.usingWrapper;
2058 app.removed = false;
2059 synchronized (mPidsSelfLocked) {
2060 this.mPidsSelfLocked.put(startResult.pid, app);
2061 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2062 msg.obj = app;
2063 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2064 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 }
2066 } catch (RuntimeException e) {
2067 // XXX do better error recovery.
2068 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002069 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071 }
2072
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002073 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 if (resumed) {
2075 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2076 } else {
2077 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2078 }
2079 }
2080
Amith Yamasani742a6712011-05-04 14:49:28 -07002081 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002082 if (mHeadless) {
2083 // Added because none of the other calls to ensureBootCompleted seem to fire
2084 // when running headless.
2085 ensureBootCompleted();
2086 return false;
2087 }
2088
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002089 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2090 && mTopAction == null) {
2091 // We are running in factory test mode, but unable to find
2092 // the factory test app, so just sit around displaying the
2093 // error message and don't try to start anything.
2094 return false;
2095 }
2096 Intent intent = new Intent(
2097 mTopAction,
2098 mTopData != null ? Uri.parse(mTopData) : null);
2099 intent.setComponent(mTopComponent);
2100 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2101 intent.addCategory(Intent.CATEGORY_HOME);
2102 }
2103 ActivityInfo aInfo =
2104 intent.resolveActivityInfo(mContext.getPackageManager(),
2105 STOCK_PM_FLAGS);
2106 if (aInfo != null) {
2107 intent.setComponent(new ComponentName(
2108 aInfo.applicationInfo.packageName, aInfo.name));
2109 // Don't do this if the home app is currently being
2110 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002111 aInfo = new ActivityInfo(aInfo);
2112 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002113 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2114 aInfo.applicationInfo.uid);
2115 if (app == null || app.instrumentationClass == null) {
2116 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002117 mMainStack.startActivityLocked(null, intent, null, aInfo,
2118 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002119 }
2120 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002121
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002122 return true;
2123 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002124
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002125 /**
2126 * Starts the "new version setup screen" if appropriate.
2127 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002128 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002129 // Only do this once per boot.
2130 if (mCheckedForSetup) {
2131 return;
2132 }
2133
2134 // We will show this screen if the current one is a different
2135 // version than the last one shown, and we are not running in
2136 // low-level factory test mode.
2137 final ContentResolver resolver = mContext.getContentResolver();
2138 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2139 Settings.Secure.getInt(resolver,
2140 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2141 mCheckedForSetup = true;
2142
2143 // See if we should be showing the platform update setup UI.
2144 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2145 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2146 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2147
2148 // We don't allow third party apps to replace this.
2149 ResolveInfo ri = null;
2150 for (int i=0; ris != null && i<ris.size(); i++) {
2151 if ((ris.get(i).activityInfo.applicationInfo.flags
2152 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2153 ri = ris.get(i);
2154 break;
2155 }
2156 }
2157
2158 if (ri != null) {
2159 String vers = ri.activityInfo.metaData != null
2160 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2161 : null;
2162 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2163 vers = ri.activityInfo.applicationInfo.metaData.getString(
2164 Intent.METADATA_SETUP_VERSION);
2165 }
2166 String lastVers = Settings.Secure.getString(
2167 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2168 if (vers != null && !vers.equals(lastVers)) {
2169 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2170 intent.setComponent(new ComponentName(
2171 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002172 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2173 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002174 }
2175 }
2176 }
2177 }
2178
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002179 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002180 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181 }
2182
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002183 void enforceNotIsolatedCaller(String caller) {
2184 if (UserId.isIsolated(Binder.getCallingUid())) {
2185 throw new SecurityException("Isolated process not allowed to call " + caller);
2186 }
2187 }
2188
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002189 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002190 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002191 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002192 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2193 }
2194 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002195
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002196 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002197 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2198 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002199 synchronized (this) {
2200 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2201 }
2202 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002203
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002204 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002205 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002206 synchronized (this) {
2207 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2208 }
2209 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002210
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002211 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002212 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2213 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002214 synchronized (this) {
2215 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002216 }
2217 }
2218
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002219 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002220 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002221 synchronized (this) {
2222 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2223 }
2224 }
2225
2226 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002227 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2228 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002229 synchronized (this) {
2230 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2231 }
2232 }
2233
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002234 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002235 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002236
2237 final int identHash = System.identityHashCode(r);
2238 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240
Jeff Sharkeya4620792011-05-20 15:29:23 -07002241 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2242 int i = mProcessObservers.beginBroadcast();
2243 while (i > 0) {
2244 i--;
2245 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2246 if (observer != null) {
2247 try {
2248 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2249 } catch (RemoteException e) {
2250 }
2251 }
2252 }
2253 mProcessObservers.finishBroadcast();
2254 }
2255
2256 private void dispatchProcessDied(int pid, int uid) {
2257 int i = mProcessObservers.beginBroadcast();
2258 while (i > 0) {
2259 i--;
2260 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2261 if (observer != null) {
2262 try {
2263 observer.onProcessDied(pid, uid);
2264 } catch (RemoteException e) {
2265 }
2266 }
2267 }
2268 mProcessObservers.finishBroadcast();
2269 }
2270
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002271 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002272 final int N = mPendingActivityLaunches.size();
2273 if (N <= 0) {
2274 return;
2275 }
2276 for (int i=0; i<N; i++) {
2277 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002278 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002279 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002280 }
2281 mPendingActivityLaunches.clear();
2282 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002283
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002284 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002285 Intent intent, String resolvedType, IBinder resultTo,
2286 String resultWho, int requestCode, int startFlags,
2287 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002288 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002289 int userId = 0;
2290 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2291 // Requesting home, set the identity to the current user
2292 // HACK!
2293 userId = mCurrentUserId;
2294 } else {
2295 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2296 // the current user's userId
2297 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2298 userId = 0;
2299 } else {
2300 userId = Binder.getOrigCallingUser();
2301 }
2302 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002303 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002304 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2305 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002306 }
2307
2308 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002309 Intent intent, String resolvedType, IBinder resultTo,
2310 String resultWho, int requestCode, int startFlags, String profileFile,
2311 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002312 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002313 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002314 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002315 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002316 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2317 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002318 return res;
2319 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002320
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002321 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002322 Intent intent, String resolvedType, IBinder resultTo,
2323 String resultWho, int requestCode, int startFlags, Configuration config,
2324 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002325 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002326 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002327 resultTo, resultWho, requestCode, startFlags,
2328 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002329 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002330 }
2331
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002332 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002333 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002334 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002335 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002336 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002337 // Refuse possible leaked file descriptors
2338 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2339 throw new IllegalArgumentException("File descriptors passed in Intent");
2340 }
2341
2342 IIntentSender sender = intent.getTarget();
2343 if (!(sender instanceof PendingIntentRecord)) {
2344 throw new IllegalArgumentException("Bad PendingIntent object");
2345 }
2346
2347 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002348
2349 synchronized (this) {
2350 // If this is coming from the currently resumed activity, it is
2351 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002352 if (mMainStack.mResumedActivity != null
2353 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002354 Binder.getCallingUid()) {
2355 mAppSwitchesAllowedTime = 0;
2356 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002357 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002358 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2359 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002360 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002361 }
2362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002364 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 // Refuse possible leaked file descriptors
2366 if (intent != null && intent.hasFileDescriptors() == true) {
2367 throw new IllegalArgumentException("File descriptors passed in Intent");
2368 }
2369
2370 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002371 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2372 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002373 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 return false;
2375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 if (r.app == null || r.app.thread == null) {
2377 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002378 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 return false;
2380 }
2381 intent = new Intent(intent);
2382 // The caller is not allowed to change the data.
2383 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2384 // And we are resetting to find the next component...
2385 intent.setComponent(null);
2386
2387 ActivityInfo aInfo = null;
2388 try {
2389 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002390 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002392 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2393 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394
2395 // Look for the original activity in the list...
2396 final int N = resolves != null ? resolves.size() : 0;
2397 for (int i=0; i<N; i++) {
2398 ResolveInfo rInfo = resolves.get(i);
2399 if (rInfo.activityInfo.packageName.equals(r.packageName)
2400 && rInfo.activityInfo.name.equals(r.info.name)) {
2401 // We found the current one... the next matching is
2402 // after it.
2403 i++;
2404 if (i<N) {
2405 aInfo = resolves.get(i).activityInfo;
2406 }
2407 break;
2408 }
2409 }
2410 } catch (RemoteException e) {
2411 }
2412
2413 if (aInfo == null) {
2414 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002415 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 return false;
2417 }
2418
2419 intent.setComponent(new ComponentName(
2420 aInfo.applicationInfo.packageName, aInfo.name));
2421 intent.setFlags(intent.getFlags()&~(
2422 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2423 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2424 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2425 Intent.FLAG_ACTIVITY_NEW_TASK));
2426
2427 // Okay now we need to start the new activity, replacing the
2428 // currently running activity. This is a little tricky because
2429 // we want to start the new one as if the current one is finished,
2430 // but not finish the current one first so that there is no flicker.
2431 // And thus...
2432 final boolean wasFinishing = r.finishing;
2433 r.finishing = true;
2434
2435 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002436 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 final String resultWho = r.resultWho;
2438 final int requestCode = r.requestCode;
2439 r.resultTo = null;
2440 if (resultTo != null) {
2441 resultTo.removeResultsLocked(r, resultWho, requestCode);
2442 }
2443
2444 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002445 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002446 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2447 resultWho, requestCode, -1, r.launchedFromUid, 0,
2448 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 Binder.restoreCallingIdentity(origId);
2450
2451 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002452 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 return false;
2454 }
2455 return true;
2456 }
2457 }
2458
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002459 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002461 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002462
2463 // This is so super not safe, that only the system (or okay root)
2464 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002465 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002466 final int callingUid = Binder.getCallingUid();
2467 if (callingUid != 0 && callingUid != Process.myUid()) {
2468 throw new SecurityException(
2469 "startActivityInPackage only available to the system");
2470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471
Amith Yamasani742a6712011-05-04 14:49:28 -07002472 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002473 resultTo, resultWho, requestCode, startFlags,
2474 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002475 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002476 }
2477
2478 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002479 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002480 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002481 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002482 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002484 }
2485
2486 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002487 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2488 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002489
2490 // This is so super not safe, that only the system (or okay root)
2491 // can do it.
2492 final int callingUid = Binder.getCallingUid();
2493 if (callingUid != 0 && callingUid != Process.myUid()) {
2494 throw new SecurityException(
2495 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002497 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002498 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
2501
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002502 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002504 // Quick case: check if the top-most recent task is the same.
2505 if (N > 0 && mRecentTasks.get(0) == task) {
2506 return;
2507 }
2508 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 for (int i=0; i<N; i++) {
2510 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002511 if (task.userId == tr.userId
2512 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2513 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 mRecentTasks.remove(i);
2515 i--;
2516 N--;
2517 if (task.intent == null) {
2518 // If the new recent task we are adding is not fully
2519 // specified, then replace it with the existing recent task.
2520 task = tr;
2521 }
2522 }
2523 }
2524 if (N >= MAX_RECENT_TASKS) {
2525 mRecentTasks.remove(N-1);
2526 }
2527 mRecentTasks.add(0, task);
2528 }
2529
2530 public void setRequestedOrientation(IBinder token,
2531 int requestedOrientation) {
2532 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002533 ActivityRecord r = mMainStack.isInStackLocked(token);
2534 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 return;
2536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002538 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002540 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002541 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 if (config != null) {
2543 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002544 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002545 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
2547 }
2548 Binder.restoreCallingIdentity(origId);
2549 }
2550 }
2551
2552 public int getRequestedOrientation(IBinder token) {
2553 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002554 ActivityRecord r = mMainStack.isInStackLocked(token);
2555 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2557 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002558 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 }
2560 }
2561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 /**
2563 * This is the internal entry point for handling Activity.finish().
2564 *
2565 * @param token The Binder token referencing the Activity we want to finish.
2566 * @param resultCode Result code, if any, from this Activity.
2567 * @param resultData Result data (Intent), if any, from this Activity.
2568 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002569 * @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 -08002570 */
2571 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2572 // Refuse possible leaked file descriptors
2573 if (resultData != null && resultData.hasFileDescriptors() == true) {
2574 throw new IllegalArgumentException("File descriptors passed in Intent");
2575 }
2576
2577 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002578 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002580 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 if (next != null) {
2582 // ask watcher if this is allowed
2583 boolean resumeOK = true;
2584 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002585 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002587 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589
2590 if (!resumeOK) {
2591 return false;
2592 }
2593 }
2594 }
2595 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 resultData, "app-request");
2598 Binder.restoreCallingIdentity(origId);
2599 return res;
2600 }
2601 }
2602
Dianne Hackborn860755f2010-06-03 18:47:52 -07002603 public final void finishHeavyWeightApp() {
2604 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2605 != PackageManager.PERMISSION_GRANTED) {
2606 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2607 + Binder.getCallingPid()
2608 + ", uid=" + Binder.getCallingUid()
2609 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2610 Slog.w(TAG, msg);
2611 throw new SecurityException(msg);
2612 }
2613
2614 synchronized(this) {
2615 if (mHeavyWeightProcess == null) {
2616 return;
2617 }
2618
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002619 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002620 mHeavyWeightProcess.activities);
2621 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002622 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002623 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002624 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002625 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002626 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002627 null, "finish-heavy");
2628 }
2629 }
2630 }
2631
2632 mHeavyWeightProcess = null;
2633 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2634 }
2635 }
2636
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002637 public void crashApplication(int uid, int initialPid, String packageName,
2638 String message) {
2639 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2640 != PackageManager.PERMISSION_GRANTED) {
2641 String msg = "Permission Denial: crashApplication() from pid="
2642 + Binder.getCallingPid()
2643 + ", uid=" + Binder.getCallingUid()
2644 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2645 Slog.w(TAG, msg);
2646 throw new SecurityException(msg);
2647 }
2648
2649 synchronized(this) {
2650 ProcessRecord proc = null;
2651
2652 // Figure out which process to kill. We don't trust that initialPid
2653 // still has any relation to current pids, so must scan through the
2654 // list.
2655 synchronized (mPidsSelfLocked) {
2656 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2657 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002658 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002659 continue;
2660 }
2661 if (p.pid == initialPid) {
2662 proc = p;
2663 break;
2664 }
2665 for (String str : p.pkgList) {
2666 if (str.equals(packageName)) {
2667 proc = p;
2668 }
2669 }
2670 }
2671 }
2672
2673 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002674 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002675 + " initialPid=" + initialPid
2676 + " packageName=" + packageName);
2677 return;
2678 }
2679
2680 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002681 if (proc.pid == Process.myPid()) {
2682 Log.w(TAG, "crashApplication: trying to crash self!");
2683 return;
2684 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002685 long ident = Binder.clearCallingIdentity();
2686 try {
2687 proc.thread.scheduleCrash(message);
2688 } catch (RemoteException e) {
2689 }
2690 Binder.restoreCallingIdentity(ident);
2691 }
2692 }
2693 }
2694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 public final void finishSubActivity(IBinder token, String resultWho,
2696 int requestCode) {
2697 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002698 ActivityRecord self = mMainStack.isInStackLocked(token);
2699 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 return;
2701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702
2703 final long origId = Binder.clearCallingIdentity();
2704
2705 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002706 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2707 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 if (r.resultTo == self && r.requestCode == requestCode) {
2709 if ((r.resultWho == null && resultWho == null) ||
2710 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002711 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 Activity.RESULT_CANCELED, null, "request-sub");
2713 }
2714 }
2715 }
2716
2717 Binder.restoreCallingIdentity(origId);
2718 }
2719 }
2720
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002721 public boolean willActivityBeVisible(IBinder token) {
2722 synchronized(this) {
2723 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002724 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2725 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002726 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002727 return true;
2728 }
2729 if (r.fullscreen && !r.finishing) {
2730 return false;
2731 }
2732 }
2733 return true;
2734 }
2735 }
2736
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002737 public void overridePendingTransition(IBinder token, String packageName,
2738 int enterAnim, int exitAnim) {
2739 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002740 ActivityRecord self = mMainStack.isInStackLocked(token);
2741 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002742 return;
2743 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002744
2745 final long origId = Binder.clearCallingIdentity();
2746
2747 if (self.state == ActivityState.RESUMED
2748 || self.state == ActivityState.PAUSING) {
2749 mWindowManager.overridePendingAppTransition(packageName,
2750 enterAnim, exitAnim);
2751 }
2752
2753 Binder.restoreCallingIdentity(origId);
2754 }
2755 }
2756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 * Main function for removing an existing process from the activity manager
2759 * as a result of that process going away. Clears out all connections
2760 * to the process.
2761 */
2762 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002763 boolean restarting, boolean allowRestart) {
2764 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002766 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 }
2768
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002769 if (mProfileProc == app) {
2770 clearProfilerLocked();
2771 }
2772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002774 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2775 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2776 mMainStack.mPausingActivity = null;
2777 }
2778 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2779 mMainStack.mLastPausedActivity = null;
2780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781
2782 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002783 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784
2785 boolean atTop = true;
2786 boolean hasVisibleActivities = false;
2787
2788 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002789 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002790 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 TAG, "Removing app " + app + " from history with " + i + " entries");
2792 while (i > 0) {
2793 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002794 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002795 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2797 if (r.app == app) {
2798 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002799 if (ActivityStack.DEBUG_ADD_REMOVE) {
2800 RuntimeException here = new RuntimeException("here");
2801 here.fillInStackTrace();
2802 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2803 + ": haveState=" + r.haveState
2804 + " stateNotNeeded=" + r.stateNotNeeded
2805 + " finishing=" + r.finishing
2806 + " state=" + r.state, here);
2807 }
2808 if (!r.finishing) {
2809 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002810 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2811 System.identityHashCode(r),
2812 r.task.taskId, r.shortComponentName,
2813 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002814 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002815 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816
2817 } else {
2818 // We have the current state for this activity, so
2819 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002820 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 TAG, "Keeping entry, setting app to null");
2822 if (r.visible) {
2823 hasVisibleActivities = true;
2824 }
2825 r.app = null;
2826 r.nowVisible = false;
2827 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002828 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2829 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 r.icicle = null;
2831 }
2832 }
2833
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002834 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836 atTop = false;
2837 }
2838
2839 app.activities.clear();
2840
2841 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002842 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 + " running instrumentation " + app.instrumentationClass);
2844 Bundle info = new Bundle();
2845 info.putString("shortMsg", "Process crashed.");
2846 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2847 }
2848
2849 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 // If there was nothing to resume, and we are not already
2852 // restarting this process, but there is a visible activity that
2853 // is hosted by the process... then make sure all visible
2854 // activities are running, taking care of restarting this
2855 // process.
2856 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 }
2859 }
2860 }
2861 }
2862
2863 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2864 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002866 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2867 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2869 return i;
2870 }
2871 }
2872 return -1;
2873 }
2874
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002875 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 IApplicationThread thread) {
2877 if (thread == null) {
2878 return null;
2879 }
2880
2881 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002882 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 }
2884
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002885 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 IApplicationThread thread) {
2887
2888 mProcDeaths[0]++;
2889
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002890 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2891 synchronized (stats) {
2892 stats.noteProcessDiedLocked(app.info.uid, pid);
2893 }
2894
Magnus Edlund7bb25812010-02-24 15:45:06 +01002895 // Clean up already done if the process has been re-started.
2896 if (app.pid == pid && app.thread != null &&
2897 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002898 if (!app.killedBackground) {
2899 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2900 + ") has died.");
2901 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002902 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002903 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 TAG, "Dying app: " + app + ", pid: " + pid
2905 + ", thread: " + thread.asBinder());
2906 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002907 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908
2909 if (doLowMem) {
2910 // If there are no longer any background processes running,
2911 // and the app that died was not running instrumentation,
2912 // then tell everyone we are now low on memory.
2913 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002914 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2915 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002916 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 haveBg = true;
2918 break;
2919 }
2920 }
2921
2922 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002923 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002924 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002925 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2926 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002927 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002928 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2929 // The low memory report is overriding any current
2930 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002931 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002932 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002933 rec.lastRequestedGc = 0;
2934 } else {
2935 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002937 rec.reportLowMemory = true;
2938 rec.lastLowMemory = now;
2939 mProcessesToGc.remove(rec);
2940 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 }
2942 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002943 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002944 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
2946 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002947 } else if (app.pid != pid) {
2948 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002949 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002950 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002951 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002952 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002953 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 + thread.asBinder());
2955 }
2956 }
2957
Dan Egnor42471dd2010-01-07 17:25:22 -08002958 /**
2959 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002960 * @param clearTraces causes the dump file to be erased prior to the new
2961 * traces being written, if true; when false, the new traces will be
2962 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002963 * @param firstPids of dalvik VM processes to dump stack traces for first
2964 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002965 * @return file containing stack traces, or null if no dump file is configured
2966 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002967 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2968 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002969 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2970 if (tracesPath == null || tracesPath.length() == 0) {
2971 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002973
2974 File tracesFile = new File(tracesPath);
2975 try {
2976 File tracesDir = tracesFile.getParentFile();
2977 if (!tracesDir.exists()) tracesFile.mkdirs();
2978 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2979
Christopher Tate6ee412d2010-05-28 12:01:56 -07002980 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002981 tracesFile.createNewFile();
2982 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2983 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002984 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002985 return null;
2986 }
2987
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002988 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2989 return tracesFile;
2990 }
2991
2992 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2993 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002994 // Use a FileObserver to detect when traces finish writing.
2995 // The order of traces is considered important to maintain for legibility.
2996 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2997 public synchronized void onEvent(int event, String path) { notify(); }
2998 };
2999
3000 try {
3001 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003002
3003 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003004 if (firstPids != null) {
3005 try {
3006 int num = firstPids.size();
3007 for (int i = 0; i < num; i++) {
3008 synchronized (observer) {
3009 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3010 observer.wait(200); // Wait for write-close, give up after 200msec
3011 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003012 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003013 } catch (InterruptedException e) {
3014 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003015 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003016 }
3017
3018 // Next measure CPU usage.
3019 if (processStats != null) {
3020 processStats.init();
3021 System.gc();
3022 processStats.update();
3023 try {
3024 synchronized (processStats) {
3025 processStats.wait(500); // measure over 1/2 second.
3026 }
3027 } catch (InterruptedException e) {
3028 }
3029 processStats.update();
3030
3031 // We'll take the stack crawls of just the top apps using CPU.
3032 final int N = processStats.countWorkingStats();
3033 int numProcs = 0;
3034 for (int i=0; i<N && numProcs<5; i++) {
3035 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3036 if (lastPids.indexOfKey(stats.pid) >= 0) {
3037 numProcs++;
3038 try {
3039 synchronized (observer) {
3040 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3041 observer.wait(200); // Wait for write-close, give up after 200msec
3042 }
3043 } catch (InterruptedException e) {
3044 Log.wtf(TAG, e);
3045 }
3046
3047 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003048 }
3049 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003050
Dan Egnor42471dd2010-01-07 17:25:22 -08003051 } finally {
3052 observer.stopWatching();
3053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 }
3055
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003056 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003057 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003058 return;
3059 }
3060 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3061 if (tracesPath == null || tracesPath.length() == 0) {
3062 return;
3063 }
3064
3065 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3066 StrictMode.allowThreadDiskWrites();
3067 try {
3068 final File tracesFile = new File(tracesPath);
3069 final File tracesDir = tracesFile.getParentFile();
3070 final File tracesTmp = new File(tracesDir, "__tmp__");
3071 try {
3072 if (!tracesDir.exists()) tracesFile.mkdirs();
3073 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3074
3075 if (tracesFile.exists()) {
3076 tracesTmp.delete();
3077 tracesFile.renameTo(tracesTmp);
3078 }
3079 StringBuilder sb = new StringBuilder();
3080 Time tobj = new Time();
3081 tobj.set(System.currentTimeMillis());
3082 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3083 sb.append(": ");
3084 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3085 sb.append(" since ");
3086 sb.append(msg);
3087 FileOutputStream fos = new FileOutputStream(tracesFile);
3088 fos.write(sb.toString().getBytes());
3089 if (app == null) {
3090 fos.write("\n*** No application process!".getBytes());
3091 }
3092 fos.close();
3093 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3094 } catch (IOException e) {
3095 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3096 return;
3097 }
3098
3099 if (app != null) {
3100 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3101 firstPids.add(app.pid);
3102 dumpStackTraces(tracesPath, firstPids, null, null);
3103 }
3104
3105 File lastTracesFile = null;
3106 File curTracesFile = null;
3107 for (int i=9; i>=0; i--) {
3108 String name = String.format("slow%02d.txt", i);
3109 curTracesFile = new File(tracesDir, name);
3110 if (curTracesFile.exists()) {
3111 if (lastTracesFile != null) {
3112 curTracesFile.renameTo(lastTracesFile);
3113 } else {
3114 curTracesFile.delete();
3115 }
3116 }
3117 lastTracesFile = curTracesFile;
3118 }
3119 tracesFile.renameTo(curTracesFile);
3120 if (tracesTmp.exists()) {
3121 tracesTmp.renameTo(tracesFile);
3122 }
3123 } finally {
3124 StrictMode.setThreadPolicy(oldPolicy);
3125 }
3126 }
3127
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003128 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3129 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003130 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3131 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3132
Dianne Hackborn287952c2010-09-22 22:34:31 -07003133 if (mController != null) {
3134 try {
3135 // 0 == continue, -1 = kill process immediately
3136 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3137 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3138 } catch (RemoteException e) {
3139 mController = null;
3140 }
3141 }
3142
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003143 long anrTime = SystemClock.uptimeMillis();
3144 if (MONITOR_CPU_USAGE) {
3145 updateCpuStatsNow();
3146 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003147
3148 synchronized (this) {
3149 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3150 if (mShuttingDown) {
3151 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3152 return;
3153 } else if (app.notResponding) {
3154 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3155 return;
3156 } else if (app.crashing) {
3157 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3158 return;
3159 }
3160
3161 // In case we come through here for the same app before completing
3162 // this one, mark as anring now so we will bail out.
3163 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003164
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003165 // Log the ANR to the event log.
3166 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3167 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003168
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003169 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003170 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003171
3172 int parentPid = app.pid;
3173 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003174 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003175
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003176 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003177
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003178 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3179 ProcessRecord r = mLruProcesses.get(i);
3180 if (r != null && r.thread != null) {
3181 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003182 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3183 if (r.persistent) {
3184 firstPids.add(pid);
3185 } else {
3186 lastPids.put(pid, Boolean.TRUE);
3187 }
3188 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 }
3191 }
3192
Dan Egnor42471dd2010-01-07 17:25:22 -08003193 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003194 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003195 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003196 info.append("ANR in ").append(app.processName);
3197 if (activity != null && activity.shortComponentName != null) {
3198 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003199 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003200 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003202 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003204 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003205 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207
Dianne Hackborn287952c2010-09-22 22:34:31 -07003208 final ProcessStats processStats = new ProcessStats(true);
3209
3210 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3211
Dan Egnor42471dd2010-01-07 17:25:22 -08003212 String cpuInfo = null;
3213 if (MONITOR_CPU_USAGE) {
3214 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003215 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003216 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003217 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003218 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003219 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
3221
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003222 info.append(processStats.printCurrentState(anrTime));
3223
Joe Onorato8a9b2202010-02-26 18:56:32 -08003224 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003225 if (tracesFile == null) {
3226 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3227 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3228 }
3229
Jeff Sharkeya353d262011-10-28 11:12:06 -07003230 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3231 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003232
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003233 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003235 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3236 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003238 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3239 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 }
3241 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003242 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 }
3244 }
3245
Dan Egnor42471dd2010-01-07 17:25:22 -08003246 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3247 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3248 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003249
3250 synchronized (this) {
3251 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003252 Slog.w(TAG, "Killing " + app + ": background ANR");
3253 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3254 app.processName, app.setAdj, "background ANR");
3255 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003256 return;
3257 }
3258
3259 // Set the app's notResponding state, and look up the errorReportReceiver
3260 makeAppNotRespondingLocked(app,
3261 activity != null ? activity.shortComponentName : null,
3262 annotation != null ? "ANR " + annotation : "ANR",
3263 info.toString());
3264
3265 // Bring up the infamous App Not Responding dialog
3266 Message msg = Message.obtain();
3267 HashMap map = new HashMap();
3268 msg.what = SHOW_NOT_RESPONDING_MSG;
3269 msg.obj = map;
3270 map.put("app", app);
3271 if (activity != null) {
3272 map.put("activity", activity);
3273 }
3274
3275 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 }
3278
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003279 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3280 if (!mLaunchWarningShown) {
3281 mLaunchWarningShown = true;
3282 mHandler.post(new Runnable() {
3283 @Override
3284 public void run() {
3285 synchronized (ActivityManagerService.this) {
3286 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3287 d.show();
3288 mHandler.postDelayed(new Runnable() {
3289 @Override
3290 public void run() {
3291 synchronized (ActivityManagerService.this) {
3292 d.dismiss();
3293 mLaunchWarningShown = false;
3294 }
3295 }
3296 }, 4000);
3297 }
3298 }
3299 });
3300 }
3301 }
3302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003304 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003305 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 int uid = Binder.getCallingUid();
3307 int pid = Binder.getCallingPid();
3308 long callingId = Binder.clearCallingIdentity();
3309 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003310 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 int pkgUid = -1;
3312 synchronized(this) {
3313 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003314 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 } catch (RemoteException e) {
3316 }
3317 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003318 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 return false;
3320 }
3321 if (uid == pkgUid || checkComponentPermission(
3322 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003323 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003325 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 } else {
3327 throw new SecurityException(pid+" does not have permission:"+
3328 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3329 "for process:"+packageName);
3330 }
3331 }
3332
3333 try {
3334 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003335 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3337 Uri.fromParts("package", packageName, null));
3338 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003339 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003340 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 } catch (RemoteException e) {
3342 }
3343 } finally {
3344 Binder.restoreCallingIdentity(callingId);
3345 }
3346 return true;
3347 }
3348
Dianne Hackborn03abb812010-01-04 18:43:19 -08003349 public void killBackgroundProcesses(final String packageName) {
3350 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3351 != PackageManager.PERMISSION_GRANTED &&
3352 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3353 != PackageManager.PERMISSION_GRANTED) {
3354 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 + Binder.getCallingPid()
3356 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003357 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003358 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 throw new SecurityException(msg);
3360 }
3361
Amith Yamasani483f3b02012-03-13 16:08:00 -07003362 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 long callingId = Binder.clearCallingIdentity();
3364 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003365 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 int pkgUid = -1;
3367 synchronized(this) {
3368 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003369 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 } catch (RemoteException e) {
3371 }
3372 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003373 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 return;
3375 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003376 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003377 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3378 }
3379 } finally {
3380 Binder.restoreCallingIdentity(callingId);
3381 }
3382 }
3383
3384 public void killAllBackgroundProcesses() {
3385 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3386 != PackageManager.PERMISSION_GRANTED) {
3387 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3388 + Binder.getCallingPid()
3389 + ", uid=" + Binder.getCallingUid()
3390 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3391 Slog.w(TAG, msg);
3392 throw new SecurityException(msg);
3393 }
3394
3395 long callingId = Binder.clearCallingIdentity();
3396 try {
3397 synchronized(this) {
3398 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3399 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3400 final int NA = apps.size();
3401 for (int ia=0; ia<NA; ia++) {
3402 ProcessRecord app = apps.valueAt(ia);
3403 if (app.persistent) {
3404 // we don't kill persistent processes
3405 continue;
3406 }
3407 if (app.removed) {
3408 procs.add(app);
3409 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3410 app.removed = true;
3411 procs.add(app);
3412 }
3413 }
3414 }
3415
3416 int N = procs.size();
3417 for (int i=0; i<N; i++) {
3418 removeProcessLocked(procs.get(i), false, true, "kill all background");
3419 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003420 }
3421 } finally {
3422 Binder.restoreCallingIdentity(callingId);
3423 }
3424 }
3425
3426 public void forceStopPackage(final String packageName) {
3427 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3428 != PackageManager.PERMISSION_GRANTED) {
3429 String msg = "Permission Denial: forceStopPackage() from pid="
3430 + Binder.getCallingPid()
3431 + ", uid=" + Binder.getCallingUid()
3432 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003433 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003434 throw new SecurityException(msg);
3435 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003436 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003437 long callingId = Binder.clearCallingIdentity();
3438 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003439 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003440 int pkgUid = -1;
3441 synchronized(this) {
3442 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003443 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003444 } catch (RemoteException e) {
3445 }
3446 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003447 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003448 return;
3449 }
3450 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003451 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003452 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003453 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003454 } catch (IllegalArgumentException e) {
3455 Slog.w(TAG, "Failed trying to unstop package "
3456 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 }
3459 } finally {
3460 Binder.restoreCallingIdentity(callingId);
3461 }
3462 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003463
3464 /*
3465 * The pkg name and uid have to be specified.
3466 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3467 */
3468 public void killApplicationWithUid(String pkg, int uid) {
3469 if (pkg == null) {
3470 return;
3471 }
3472 // Make sure the uid is valid.
3473 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003474 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003475 return;
3476 }
3477 int callerUid = Binder.getCallingUid();
3478 // Only the system server can kill an application
3479 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003480 // Post an aysnc message to kill the application
3481 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3482 msg.arg1 = uid;
3483 msg.arg2 = 0;
3484 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003485 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003486 } else {
3487 throw new SecurityException(callerUid + " cannot kill pkg: " +
3488 pkg);
3489 }
3490 }
3491
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003492 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003493 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003494 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003495 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003496 if (reason != null) {
3497 intent.putExtra("reason", reason);
3498 }
3499
3500 final int uid = Binder.getCallingUid();
3501 final long origId = Binder.clearCallingIdentity();
3502 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003503 mWindowManager.closeSystemDialogs(reason);
3504
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003505 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003506 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003507 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003508 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003509 Activity.RESULT_CANCELED, null, "close-sys");
3510 }
3511 }
3512
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003513 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003514 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003515 }
3516 Binder.restoreCallingIdentity(origId);
3517 }
3518
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003519 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003520 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003521 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003522 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3523 for (int i=pids.length-1; i>=0; i--) {
3524 infos[i] = new Debug.MemoryInfo();
3525 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003526 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003527 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003528 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003529
Dianne Hackbornb437e092011-08-05 17:50:29 -07003530 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003531 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003532 long[] pss = new long[pids.length];
3533 for (int i=pids.length-1; i>=0; i--) {
3534 pss[i] = Debug.getPss(pids[i]);
3535 }
3536 return pss;
3537 }
3538
Christopher Tate5e1ab332009-09-01 20:32:49 -07003539 public void killApplicationProcess(String processName, int uid) {
3540 if (processName == null) {
3541 return;
3542 }
3543
3544 int callerUid = Binder.getCallingUid();
3545 // Only the system server can kill an application
3546 if (callerUid == Process.SYSTEM_UID) {
3547 synchronized (this) {
3548 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003549 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003550 try {
3551 app.thread.scheduleSuicide();
3552 } catch (RemoteException e) {
3553 // If the other end already died, then our work here is done.
3554 }
3555 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003556 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003557 + processName + " / " + uid);
3558 }
3559 }
3560 } else {
3561 throw new SecurityException(callerUid + " cannot kill app process: " +
3562 processName);
3563 }
3564 }
3565
Dianne Hackborn03abb812010-01-04 18:43:19 -08003566 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003567 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3569 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003570 if (!mProcessesReady) {
3571 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 intent.putExtra(Intent.EXTRA_UID, uid);
3574 broadcastIntentLocked(null, null, intent,
3575 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003576 false, false,
3577 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 }
3579
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003580 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003581 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003582 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003583 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 // Remove all processes this package may have touched: all with the
3586 // same UID (except for the system or root user), and all whose name
3587 // matches the package name.
3588 final String procNamePrefix = packageName + ":";
3589 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3590 final int NA = apps.size();
3591 for (int ia=0; ia<NA; ia++) {
3592 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003593 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003594 // we don't kill persistent processes
3595 continue;
3596 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003597 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003598 if (doit) {
3599 procs.add(app);
3600 }
Amith Yamasani13593602012-03-22 16:16:17 -07003601 // If uid is specified and the uid and process name match
3602 // Or, the uid is not specified and the process name matches
3603 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003604 || ((app.processName.equals(packageName)
3605 || app.processName.startsWith(procNamePrefix))
3606 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003607 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003608 if (!doit) {
3609 return true;
3610 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003611 app.removed = true;
3612 procs.add(app);
3613 }
3614 }
3615 }
3616 }
3617
3618 int N = procs.size();
3619 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003620 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003621 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003622 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003623 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003624
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003625 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003626 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003627 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003628 int i;
3629 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 if (uid < 0) {
3632 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003633 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 } catch (RemoteException e) {
3635 }
3636 }
3637
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003638 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003639 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003640
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003641 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3642 while (badApps.hasNext()) {
3643 SparseArray<Long> ba = badApps.next();
3644 if (ba.get(uid) != null) {
3645 badApps.remove();
3646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 }
3648 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003649
3650 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003651 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003653 TaskRecord lastTask = null;
3654 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003655 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003656 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003657 if (r.userId == userId
3658 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003659 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003660 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003661 if (r.finishing) {
3662 // If this activity is just finishing, then it is not
3663 // interesting as far as something to stop.
3664 continue;
3665 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003666 return true;
3667 }
3668 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003669 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003670 if (samePackage) {
3671 if (r.app != null) {
3672 r.app.removed = true;
3673 }
3674 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003676 lastTask = r.task;
3677 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003678 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003679 i--;
3680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 }
3682 }
3683
3684 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003685 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003686 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003687 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003688 if (!doit) {
3689 return true;
3690 }
3691 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003692 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 if (service.app != null) {
3694 service.app.removed = true;
3695 }
3696 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003697 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 services.add(service);
3699 }
3700 }
3701
3702 N = services.size();
3703 for (i=0; i<N; i++) {
3704 bringDownServiceLocked(services.get(i), true);
3705 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003706
3707 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003708 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003709 if (provider.info.packageName.equals(name)
3710 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3711 if (!doit) {
3712 return true;
3713 }
3714 didSomething = true;
3715 providers.add(provider);
3716 }
3717 }
3718
3719 N = providers.size();
3720 for (i=0; i<N; i++) {
3721 removeDyingProviderLocked(null, providers.get(i));
3722 }
3723
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003724 if (doit) {
3725 if (purgeCache) {
3726 AttributeCache ac = AttributeCache.instance();
3727 if (ac != null) {
3728 ac.removePackage(name);
3729 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003730 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003731 if (mBooted) {
3732 mMainStack.resumeTopActivityLocked(null);
3733 mMainStack.scheduleIdleLocked();
3734 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003735 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003736
3737 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
3739
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003740 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003741 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003743 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003744 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003745 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 + "/" + uid + ")");
3747
3748 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003749 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003750 if (mHeavyWeightProcess == app) {
3751 mHeavyWeightProcess = null;
3752 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 boolean needRestart = false;
3755 if (app.pid > 0 && app.pid != MY_PID) {
3756 int pid = app.pid;
3757 synchronized (mPidsSelfLocked) {
3758 mPidsSelfLocked.remove(pid);
3759 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3760 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003761 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003762 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003763 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003764 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003766 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003768 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 } else {
3770 needRestart = true;
3771 }
3772 }
3773 } else {
3774 mRemovedProcesses.add(app);
3775 }
3776
3777 return needRestart;
3778 }
3779
3780 private final void processStartTimedOutLocked(ProcessRecord app) {
3781 final int pid = app.pid;
3782 boolean gone = false;
3783 synchronized (mPidsSelfLocked) {
3784 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3785 if (knownApp != null && knownApp.thread == null) {
3786 mPidsSelfLocked.remove(pid);
3787 gone = true;
3788 }
3789 }
3790
3791 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003792 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003793 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003794 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003795 mProcessNames.remove(app.processName, app.uid);
3796 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003797 if (mHeavyWeightProcess == app) {
3798 mHeavyWeightProcess = null;
3799 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3800 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003801 // Take care of any launching providers waiting for this process.
3802 checkAppInLaunchingProvidersLocked(app, true);
3803 // Take care of any services that are waiting for the process.
3804 for (int i=0; i<mPendingServices.size(); i++) {
3805 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003806 if ((app.uid == sr.appInfo.uid
3807 && app.processName.equals(sr.processName))
3808 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003809 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003810 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003811 mPendingServices.remove(i);
3812 i--;
3813 bringDownServiceLocked(sr, true);
3814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003816 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3817 app.processName, app.setAdj, "start timeout");
3818 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003819 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003820 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003821 try {
3822 IBackupManager bm = IBackupManager.Stub.asInterface(
3823 ServiceManager.getService(Context.BACKUP_SERVICE));
3824 bm.agentDisconnected(app.info.packageName);
3825 } catch (RemoteException e) {
3826 // Can't happen; the backup manager is local
3827 }
3828 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003829 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003830 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003831 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003834 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 }
3836 }
3837
3838 private final boolean attachApplicationLocked(IApplicationThread thread,
3839 int pid) {
3840
3841 // Find the application record that is being attached... either via
3842 // the pid if we are running in multiple processes, or just pull the
3843 // next app record if we are emulating process with anonymous threads.
3844 ProcessRecord app;
3845 if (pid != MY_PID && pid >= 0) {
3846 synchronized (mPidsSelfLocked) {
3847 app = mPidsSelfLocked.get(pid);
3848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 } else {
3850 app = null;
3851 }
3852
3853 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003854 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003856 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003858 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 } else {
3860 try {
3861 thread.scheduleExit();
3862 } catch (Exception e) {
3863 // Ignore exceptions.
3864 }
3865 }
3866 return false;
3867 }
3868
3869 // If this application record is still attached to a previous
3870 // process, clean it up now.
3871 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003872 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 }
3874
3875 // Tell the process all about itself.
3876
Joe Onorato8a9b2202010-02-26 18:56:32 -08003877 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 TAG, "Binding process pid " + pid + " to record " + app);
3879
3880 String processName = app.processName;
3881 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003882 AppDeathRecipient adr = new AppDeathRecipient(
3883 app, pid, thread);
3884 thread.asBinder().linkToDeath(adr, 0);
3885 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 } catch (RemoteException e) {
3887 app.resetPackageList();
3888 startProcessLocked(app, "link fail", processName);
3889 return false;
3890 }
3891
Doug Zongker2bec3d42009-12-04 12:52:44 -08003892 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893
3894 app.thread = thread;
3895 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003896 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3897 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 app.forcingToForeground = null;
3899 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003900 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 app.debugging = false;
3902
3903 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3904
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003905 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003906 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003908 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003909 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003910 }
3911
Joe Onorato8a9b2202010-02-26 18:56:32 -08003912 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 TAG, "New app record " + app
3914 + " thread=" + thread.asBinder() + " pid=" + pid);
3915 try {
3916 int testMode = IApplicationThread.DEBUG_OFF;
3917 if (mDebugApp != null && mDebugApp.equals(processName)) {
3918 testMode = mWaitForDebugger
3919 ? IApplicationThread.DEBUG_WAIT
3920 : IApplicationThread.DEBUG_ON;
3921 app.debugging = true;
3922 if (mDebugTransient) {
3923 mDebugApp = mOrigDebugApp;
3924 mWaitForDebugger = mOrigWaitForDebugger;
3925 }
3926 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003927 String profileFile = app.instrumentationProfileFile;
3928 ParcelFileDescriptor profileFd = null;
3929 boolean profileAutoStop = false;
3930 if (mProfileApp != null && mProfileApp.equals(processName)) {
3931 mProfileProc = app;
3932 profileFile = mProfileFile;
3933 profileFd = mProfileFd;
3934 profileAutoStop = mAutoStopProfiler;
3935 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003936 boolean enableOpenGlTrace = false;
3937 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3938 enableOpenGlTrace = true;
3939 mOpenGlTraceApp = null;
3940 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003941
Christopher Tate181fafa2009-05-14 11:12:14 -07003942 // If the app is being launched for restore or full backup, set it up specially
3943 boolean isRestrictedBackupMode = false;
3944 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3945 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003946 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003947 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3948 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003949
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003950 ensurePackageDexOpt(app.instrumentationInfo != null
3951 ? app.instrumentationInfo.packageName
3952 : app.info.packageName);
3953 if (app.instrumentationClass != null) {
3954 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003955 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003956 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003957 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003958 ApplicationInfo appInfo = app.instrumentationInfo != null
3959 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003960 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003961 if (profileFd != null) {
3962 profileFd = profileFd.dup();
3963 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003964 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003965 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003966 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3967 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003968 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003969 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003970 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003971 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 } catch (Exception e) {
3973 // todo: Yikes! What should we do? For now we will try to
3974 // start another process, but that could easily get us in
3975 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003976 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977
3978 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003979 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 startProcessLocked(app, "bind fail", processName);
3981 return false;
3982 }
3983
3984 // Remove this record from the list of starting applications.
3985 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003986 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3987 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 mProcessesOnHold.remove(app);
3989
3990 boolean badApp = false;
3991 boolean didSomething = false;
3992
3993 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003995 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003996 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 && processName.equals(hr.processName)) {
3998 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003999 if (mHeadless) {
4000 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4001 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 didSomething = true;
4003 }
4004 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004005 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 + hr.intent.getComponent().flattenToShortString(), e);
4007 badApp = true;
4008 }
4009 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004010 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012 }
4013
4014 // Find any services that should be running in this process...
4015 if (!badApp && mPendingServices.size() > 0) {
4016 ServiceRecord sr = null;
4017 try {
4018 for (int i=0; i<mPendingServices.size(); i++) {
4019 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004020 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4021 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 continue;
4023 }
4024
4025 mPendingServices.remove(i);
4026 i--;
4027 realStartServiceLocked(sr, app);
4028 didSomething = true;
4029 }
4030 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004031 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 + sr.shortName, e);
4033 badApp = true;
4034 }
4035 }
4036
Christopher Tatef46723b2012-01-26 14:19:24 -08004037 // Check if a next-broadcast receiver is in this process...
4038 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004040 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004042 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 }
4045 }
4046
Christopher Tate181fafa2009-05-14 11:12:14 -07004047 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004048 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004049 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004050 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004051 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004052 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4053 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4054 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004055 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004056 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004057 e.printStackTrace();
4058 }
4059 }
4060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 if (badApp) {
4062 // todo: Also need to kill application to deal with all
4063 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004064 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 return false;
4066 }
4067
4068 if (!didSomething) {
4069 updateOomAdjLocked();
4070 }
4071
4072 return true;
4073 }
4074
4075 public final void attachApplication(IApplicationThread thread) {
4076 synchronized (this) {
4077 int callingPid = Binder.getCallingPid();
4078 final long origId = Binder.clearCallingIdentity();
4079 attachApplicationLocked(thread, callingPid);
4080 Binder.restoreCallingIdentity(origId);
4081 }
4082 }
4083
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004084 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004086 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4087 if (stopProfiling) {
4088 synchronized (this) {
4089 if (mProfileProc == r.app) {
4090 if (mProfileFd != null) {
4091 try {
4092 mProfileFd.close();
4093 } catch (IOException e) {
4094 }
4095 clearProfilerLocked();
4096 }
4097 }
4098 }
4099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 Binder.restoreCallingIdentity(origId);
4101 }
4102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004104 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004105 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 mWindowManager.enableScreenAfterBoot();
4107 }
4108
Dianne Hackborn661cd522011-08-22 00:26:20 -07004109 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004110 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004111 mWindowManager.showBootMessage(msg, always);
4112 }
4113
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004114 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004115 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004116 synchronized (this) {
4117 mMainStack.dismissKeyguardOnNextActivityLocked();
4118 }
4119 }
4120
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004121 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004122 IntentFilter pkgFilter = new IntentFilter();
4123 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4124 pkgFilter.addDataScheme("package");
4125 mContext.registerReceiver(new BroadcastReceiver() {
4126 @Override
4127 public void onReceive(Context context, Intent intent) {
4128 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4129 if (pkgs != null) {
4130 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004131 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004132 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4133 setResultCode(Activity.RESULT_OK);
4134 return;
4135 }
4136 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004137 }
4138 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004139 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004140 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004141
4142 IntentFilter userFilter = new IntentFilter();
4143 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4144 mContext.registerReceiver(new BroadcastReceiver() {
4145 @Override
4146 public void onReceive(Context context, Intent intent) {
4147 onUserRemoved(intent);
4148 }
4149 }, userFilter);
4150
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004151 synchronized (this) {
4152 // Ensure that any processes we had put on hold are now started
4153 // up.
4154 final int NP = mProcessesOnHold.size();
4155 if (NP > 0) {
4156 ArrayList<ProcessRecord> procs =
4157 new ArrayList<ProcessRecord>(mProcessesOnHold);
4158 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004159 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4160 + procs.get(ip));
4161 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004162 }
4163 }
4164
4165 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004166 // Start looking for apps that are abusing wake locks.
4167 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004168 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004169 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004170 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004171 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004172 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004173 broadcastIntentLocked(null, null,
4174 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4175 null, null, 0, null, null,
4176 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004177 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004178 }
4179 }
4180 }
4181
4182 final void ensureBootCompleted() {
4183 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004184 boolean enableScreen;
4185 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004186 booting = mBooting;
4187 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004188 enableScreen = !mBooted;
4189 mBooted = true;
4190 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004191
4192 if (booting) {
4193 finishBooting();
4194 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004195
4196 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004197 enableScreenAfterBoot();
4198 }
4199 }
4200
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004201 public final void activityPaused(IBinder token) {
4202 final long origId = Binder.clearCallingIdentity();
4203 mMainStack.activityPaused(token, false);
4204 Binder.restoreCallingIdentity(origId);
4205 }
4206
4207 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4208 CharSequence description) {
4209 if (localLOGV) Slog.v(
4210 TAG, "Activity stopped: token=" + token);
4211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 // Refuse possible leaked file descriptors
4213 if (icicle != null && icicle.hasFileDescriptors()) {
4214 throw new IllegalArgumentException("File descriptors passed in Bundle");
4215 }
4216
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004217 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218
4219 final long origId = Binder.clearCallingIdentity();
4220
4221 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004222 r = mMainStack.isInStackLocked(token);
4223 if (r != null) {
4224 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 }
4226 }
4227
4228 if (r != null) {
4229 sendPendingThumbnail(r, null, null, null, false);
4230 }
4231
4232 trimApplications();
4233
4234 Binder.restoreCallingIdentity(origId);
4235 }
4236
4237 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004238 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004239 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
4241
4242 public String getCallingPackage(IBinder token) {
4243 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004244 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004245 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 }
4247 }
4248
4249 public ComponentName getCallingActivity(IBinder token) {
4250 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004251 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 return r != null ? r.intent.getComponent() : null;
4253 }
4254 }
4255
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004256 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004257 ActivityRecord r = mMainStack.isInStackLocked(token);
4258 if (r == null) {
4259 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004261 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 }
4263
4264 public ComponentName getActivityClassForToken(IBinder token) {
4265 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004266 ActivityRecord r = mMainStack.isInStackLocked(token);
4267 if (r == null) {
4268 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004270 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 }
4272 }
4273
4274 public String getPackageForToken(IBinder token) {
4275 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004276 ActivityRecord r = mMainStack.isInStackLocked(token);
4277 if (r == null) {
4278 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004280 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 }
4282 }
4283
4284 public IIntentSender getIntentSender(int type,
4285 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004286 int requestCode, Intent[] intents, String[] resolvedTypes,
4287 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004288 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004290 if (intents != null) {
4291 if (intents.length < 1) {
4292 throw new IllegalArgumentException("Intents array length must be >= 1");
4293 }
4294 for (int i=0; i<intents.length; i++) {
4295 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004296 if (intent != null) {
4297 if (intent.hasFileDescriptors()) {
4298 throw new IllegalArgumentException("File descriptors passed in Intent");
4299 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004300 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004301 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4302 throw new IllegalArgumentException(
4303 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4304 }
4305 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004306 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004307 }
4308 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004309 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004310 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004311 }
4312 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004313 if (options != null) {
4314 if (options.hasFileDescriptors()) {
4315 throw new IllegalArgumentException("File descriptors passed in options");
4316 }
4317 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 synchronized(this) {
4320 int callingUid = Binder.getCallingUid();
4321 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004322 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004323 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004324 .getPackageUid(packageName, UserId.getUserId(callingUid));
4325 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 String msg = "Permission Denial: getIntentSender() from pid="
4327 + Binder.getCallingPid()
4328 + ", uid=" + Binder.getCallingUid()
4329 + ", (need uid=" + uid + ")"
4330 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004331 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 throw new SecurityException(msg);
4333 }
4334 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004335
Amith Yamasani742a6712011-05-04 14:49:28 -07004336 if (DEBUG_MU)
4337 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4338 + Binder.getOrigCallingUid());
4339 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004340 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 } catch (RemoteException e) {
4343 throw new SecurityException(e);
4344 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004345 }
4346 }
4347
4348 IIntentSender getIntentSenderLocked(int type,
4349 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004350 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4351 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004352 if (DEBUG_MU)
4353 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004354 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004355 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004356 activity = mMainStack.isInStackLocked(token);
4357 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004358 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004360 if (activity.finishing) {
4361 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004363 }
4364
4365 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4366 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4367 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4368 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4369 |PendingIntent.FLAG_UPDATE_CURRENT);
4370
4371 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4372 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004373 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004374 WeakReference<PendingIntentRecord> ref;
4375 ref = mIntentSenderRecords.get(key);
4376 PendingIntentRecord rec = ref != null ? ref.get() : null;
4377 if (rec != null) {
4378 if (!cancelCurrent) {
4379 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004380 if (rec.key.requestIntent != null) {
4381 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4382 }
4383 if (intents != null) {
4384 intents[intents.length-1] = rec.key.requestIntent;
4385 rec.key.allIntents = intents;
4386 rec.key.allResolvedTypes = resolvedTypes;
4387 } else {
4388 rec.key.allIntents = null;
4389 rec.key.allResolvedTypes = null;
4390 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 return rec;
4393 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004394 rec.canceled = true;
4395 mIntentSenderRecords.remove(key);
4396 }
4397 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 return rec;
4399 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004400 rec = new PendingIntentRecord(this, key, callingUid);
4401 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004402 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004403 if (activity.pendingResults == null) {
4404 activity.pendingResults
4405 = new HashSet<WeakReference<PendingIntentRecord>>();
4406 }
4407 activity.pendingResults.add(rec.ref);
4408 }
4409 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 }
4411
4412 public void cancelIntentSender(IIntentSender sender) {
4413 if (!(sender instanceof PendingIntentRecord)) {
4414 return;
4415 }
4416 synchronized(this) {
4417 PendingIntentRecord rec = (PendingIntentRecord)sender;
4418 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004419 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004420 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004421 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 String msg = "Permission Denial: cancelIntentSender() from pid="
4423 + Binder.getCallingPid()
4424 + ", uid=" + Binder.getCallingUid()
4425 + " is not allowed to cancel packges "
4426 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004427 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 throw new SecurityException(msg);
4429 }
4430 } catch (RemoteException e) {
4431 throw new SecurityException(e);
4432 }
4433 cancelIntentSenderLocked(rec, true);
4434 }
4435 }
4436
4437 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4438 rec.canceled = true;
4439 mIntentSenderRecords.remove(rec.key);
4440 if (cleanActivity && rec.key.activity != null) {
4441 rec.key.activity.pendingResults.remove(rec.ref);
4442 }
4443 }
4444
4445 public String getPackageForIntentSender(IIntentSender pendingResult) {
4446 if (!(pendingResult instanceof PendingIntentRecord)) {
4447 return null;
4448 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004449 try {
4450 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4451 return res.key.packageName;
4452 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 }
4454 return null;
4455 }
4456
Christopher Tatec4a07d12012-04-06 14:19:13 -07004457 public int getUidForIntentSender(IIntentSender sender) {
4458 if (sender instanceof PendingIntentRecord) {
4459 try {
4460 PendingIntentRecord res = (PendingIntentRecord)sender;
4461 return res.uid;
4462 } catch (ClassCastException e) {
4463 }
4464 }
4465 return -1;
4466 }
4467
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004468 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4469 if (!(pendingResult instanceof PendingIntentRecord)) {
4470 return false;
4471 }
4472 try {
4473 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4474 if (res.key.allIntents == null) {
4475 return false;
4476 }
4477 for (int i=0; i<res.key.allIntents.length; i++) {
4478 Intent intent = res.key.allIntents[i];
4479 if (intent.getPackage() != null && intent.getComponent() != null) {
4480 return false;
4481 }
4482 }
4483 return true;
4484 } catch (ClassCastException e) {
4485 }
4486 return false;
4487 }
4488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 public void setProcessLimit(int max) {
4490 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4491 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004492 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004493 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004494 mProcessLimitOverride = max;
4495 }
4496 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498
4499 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004500 synchronized (this) {
4501 return mProcessLimitOverride;
4502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 }
4504
4505 void foregroundTokenDied(ForegroundToken token) {
4506 synchronized (ActivityManagerService.this) {
4507 synchronized (mPidsSelfLocked) {
4508 ForegroundToken cur
4509 = mForegroundProcesses.get(token.pid);
4510 if (cur != token) {
4511 return;
4512 }
4513 mForegroundProcesses.remove(token.pid);
4514 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4515 if (pr == null) {
4516 return;
4517 }
4518 pr.forcingToForeground = null;
4519 pr.foregroundServices = false;
4520 }
4521 updateOomAdjLocked();
4522 }
4523 }
4524
4525 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4526 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4527 "setProcessForeground()");
4528 synchronized(this) {
4529 boolean changed = false;
4530
4531 synchronized (mPidsSelfLocked) {
4532 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004533 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004534 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 return;
4536 }
4537 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4538 if (oldToken != null) {
4539 oldToken.token.unlinkToDeath(oldToken, 0);
4540 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004541 if (pr != null) {
4542 pr.forcingToForeground = null;
4543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 changed = true;
4545 }
4546 if (isForeground && token != null) {
4547 ForegroundToken newToken = new ForegroundToken() {
4548 public void binderDied() {
4549 foregroundTokenDied(this);
4550 }
4551 };
4552 newToken.pid = pid;
4553 newToken.token = token;
4554 try {
4555 token.linkToDeath(newToken, 0);
4556 mForegroundProcesses.put(pid, newToken);
4557 pr.forcingToForeground = token;
4558 changed = true;
4559 } catch (RemoteException e) {
4560 // If the process died while doing this, we will later
4561 // do the cleanup with the process death link.
4562 }
4563 }
4564 }
4565
4566 if (changed) {
4567 updateOomAdjLocked();
4568 }
4569 }
4570 }
4571
4572 // =========================================================
4573 // PERMISSIONS
4574 // =========================================================
4575
4576 static class PermissionController extends IPermissionController.Stub {
4577 ActivityManagerService mActivityManagerService;
4578 PermissionController(ActivityManagerService activityManagerService) {
4579 mActivityManagerService = activityManagerService;
4580 }
4581
4582 public boolean checkPermission(String permission, int pid, int uid) {
4583 return mActivityManagerService.checkPermission(permission, pid,
4584 uid) == PackageManager.PERMISSION_GRANTED;
4585 }
4586 }
4587
4588 /**
4589 * This can be called with or without the global lock held.
4590 */
4591 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004592 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 // We might be performing an operation on behalf of an indirect binder
4594 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4595 // client identity accordingly before proceeding.
4596 Identity tlsIdentity = sCallerIdentity.get();
4597 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004598 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4600 uid = tlsIdentity.uid;
4601 pid = tlsIdentity.pid;
4602 }
4603
4604 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004605 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 return PackageManager.PERMISSION_GRANTED;
4607 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004608 // Isolated processes don't get any permissions.
4609 if (UserId.isIsolated(uid)) {
4610 return PackageManager.PERMISSION_DENIED;
4611 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004612 // If there is a uid that owns whatever is being accessed, it has
4613 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004614 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004615 return PackageManager.PERMISSION_GRANTED;
4616 }
4617 // If the target is not exported, then nobody else can get to it.
4618 if (!exported) {
4619 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 return PackageManager.PERMISSION_DENIED;
4621 }
4622 if (permission == null) {
4623 return PackageManager.PERMISSION_GRANTED;
4624 }
4625 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004626 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 .checkUidPermission(permission, uid);
4628 } catch (RemoteException e) {
4629 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004630 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 }
4632 return PackageManager.PERMISSION_DENIED;
4633 }
4634
4635 /**
4636 * As the only public entry point for permissions checking, this method
4637 * can enforce the semantic that requesting a check on a null global
4638 * permission is automatically denied. (Internally a null permission
4639 * string is used when calling {@link #checkComponentPermission} in cases
4640 * when only uid-based security is needed.)
4641 *
4642 * This can be called with or without the global lock held.
4643 */
4644 public int checkPermission(String permission, int pid, int uid) {
4645 if (permission == null) {
4646 return PackageManager.PERMISSION_DENIED;
4647 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004648 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 }
4650
4651 /**
4652 * Binder IPC calls go through the public entry point.
4653 * This can be called with or without the global lock held.
4654 */
4655 int checkCallingPermission(String permission) {
4656 return checkPermission(permission,
4657 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004658 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004659 }
4660
4661 /**
4662 * This can be called with or without the global lock held.
4663 */
4664 void enforceCallingPermission(String permission, String func) {
4665 if (checkCallingPermission(permission)
4666 == PackageManager.PERMISSION_GRANTED) {
4667 return;
4668 }
4669
4670 String msg = "Permission Denial: " + func + " from pid="
4671 + Binder.getCallingPid()
4672 + ", uid=" + Binder.getCallingUid()
4673 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004674 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 throw new SecurityException(msg);
4676 }
4677
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004678 /**
4679 * Determine if UID is holding permissions required to access {@link Uri} in
4680 * the given {@link ProviderInfo}. Final permission checking is always done
4681 * in {@link ContentProvider}.
4682 */
4683 private final boolean checkHoldingPermissionsLocked(
4684 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004685 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4686 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004687
4688 if (pi.applicationInfo.uid == uid) {
4689 return true;
4690 } else if (!pi.exported) {
4691 return false;
4692 }
4693
4694 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4695 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004697 // check if target holds top-level <provider> permissions
4698 if (!readMet && pi.readPermission != null
4699 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4700 readMet = true;
4701 }
4702 if (!writeMet && pi.writePermission != null
4703 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4704 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004706
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004707 // track if unprotected read/write is allowed; any denied
4708 // <path-permission> below removes this ability
4709 boolean allowDefaultRead = pi.readPermission == null;
4710 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004711
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004712 // check if target holds any <path-permission> that match uri
4713 final PathPermission[] pps = pi.pathPermissions;
4714 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004715 final String path = uri.getPath();
4716 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004717 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004718 i--;
4719 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004720 if (pp.match(path)) {
4721 if (!readMet) {
4722 final String pprperm = pp.getReadPermission();
4723 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4724 + pprperm + " for " + pp.getPath()
4725 + ": match=" + pp.match(path)
4726 + " check=" + pm.checkUidPermission(pprperm, uid));
4727 if (pprperm != null) {
4728 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4729 readMet = true;
4730 } else {
4731 allowDefaultRead = false;
4732 }
4733 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004734 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004735 if (!writeMet) {
4736 final String ppwperm = pp.getWritePermission();
4737 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4738 + ppwperm + " for " + pp.getPath()
4739 + ": match=" + pp.match(path)
4740 + " check=" + pm.checkUidPermission(ppwperm, uid));
4741 if (ppwperm != null) {
4742 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4743 writeMet = true;
4744 } else {
4745 allowDefaultWrite = false;
4746 }
4747 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004748 }
4749 }
4750 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004751 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004752
4753 // grant unprotected <provider> read/write, if not blocked by
4754 // <path-permission> above
4755 if (allowDefaultRead) readMet = true;
4756 if (allowDefaultWrite) writeMet = true;
4757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 } catch (RemoteException e) {
4759 return false;
4760 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004761
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004762 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763 }
4764
4765 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4766 int modeFlags) {
4767 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004768 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 return true;
4770 }
4771 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4772 if (perms == null) return false;
4773 UriPermission perm = perms.get(uri);
4774 if (perm == null) return false;
4775 return (modeFlags&perm.modeFlags) == modeFlags;
4776 }
4777
4778 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004779 enforceNotIsolatedCaller("checkUriPermission");
4780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004781 // Another redirected-binder-call permissions check as in
4782 // {@link checkComponentPermission}.
4783 Identity tlsIdentity = sCallerIdentity.get();
4784 if (tlsIdentity != null) {
4785 uid = tlsIdentity.uid;
4786 pid = tlsIdentity.pid;
4787 }
4788
Amith Yamasani742a6712011-05-04 14:49:28 -07004789 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 // Our own process gets to do everything.
4791 if (pid == MY_PID) {
4792 return PackageManager.PERMISSION_GRANTED;
4793 }
4794 synchronized(this) {
4795 return checkUriPermissionLocked(uri, uid, modeFlags)
4796 ? PackageManager.PERMISSION_GRANTED
4797 : PackageManager.PERMISSION_DENIED;
4798 }
4799 }
4800
Dianne Hackborn39792d22010-08-19 18:01:52 -07004801 /**
4802 * Check if the targetPkg can be granted permission to access uri by
4803 * the callingUid using the given modeFlags. Throws a security exception
4804 * if callingUid is not allowed to do this. Returns the uid of the target
4805 * if the URI permission grant should be performed; returns -1 if it is not
4806 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004807 * If you already know the uid of the target, you can supply it in
4808 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004809 */
4810 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004811 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4813 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4814 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004815 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 }
4817
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004818 if (targetPkg != null) {
4819 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4820 "Checking grant " + targetPkg + " permission to " + uri);
4821 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004822
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004823 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824
4825 // If this is not a content: uri, we can't do anything with it.
4826 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004827 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004828 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004829 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 }
4831
4832 String name = uri.getAuthority();
4833 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004834 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4835 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836 if (cpr != null) {
4837 pi = cpr.info;
4838 } else {
4839 try {
4840 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004841 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 } catch (RemoteException ex) {
4843 }
4844 }
4845 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004846 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004847 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 }
4849
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004850 int targetUid = lastTargetUid;
4851 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004852 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004853 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004854 if (targetUid < 0) {
4855 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4856 "Can't grant URI permission no uid for: " + targetPkg);
4857 return -1;
4858 }
4859 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004860 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004862 }
4863
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004864 if (targetUid >= 0) {
4865 // First... does the target actually need this permission?
4866 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4867 // No need to grant the target this permission.
4868 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4869 "Target " + targetPkg + " already has full permission to " + uri);
4870 return -1;
4871 }
4872 } else {
4873 // First... there is no target package, so can anyone access it?
4874 boolean allowed = pi.exported;
4875 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4876 if (pi.readPermission != null) {
4877 allowed = false;
4878 }
4879 }
4880 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4881 if (pi.writePermission != null) {
4882 allowed = false;
4883 }
4884 }
4885 if (allowed) {
4886 return -1;
4887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 }
4889
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004890 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 if (!pi.grantUriPermissions) {
4892 throw new SecurityException("Provider " + pi.packageName
4893 + "/" + pi.name
4894 + " does not allow granting of Uri permissions (uri "
4895 + uri + ")");
4896 }
4897 if (pi.uriPermissionPatterns != null) {
4898 final int N = pi.uriPermissionPatterns.length;
4899 boolean allowed = false;
4900 for (int i=0; i<N; i++) {
4901 if (pi.uriPermissionPatterns[i] != null
4902 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4903 allowed = true;
4904 break;
4905 }
4906 }
4907 if (!allowed) {
4908 throw new SecurityException("Provider " + pi.packageName
4909 + "/" + pi.name
4910 + " does not allow granting of permission to path of Uri "
4911 + uri);
4912 }
4913 }
4914
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004915 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004917 if (callingUid != Process.myUid()) {
4918 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4919 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4920 throw new SecurityException("Uid " + callingUid
4921 + " does not have permission to uri " + uri);
4922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 }
4924 }
4925
Dianne Hackborn39792d22010-08-19 18:01:52 -07004926 return targetUid;
4927 }
4928
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004929 public int checkGrantUriPermission(int callingUid, String targetPkg,
4930 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004931 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004932 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004933 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004934 }
4935 }
4936
Dianne Hackborn39792d22010-08-19 18:01:52 -07004937 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4938 Uri uri, int modeFlags, UriPermissionOwner owner) {
4939 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4940 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4941 if (modeFlags == 0) {
4942 return;
4943 }
4944
4945 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 // to the uri, and the target doesn't. Let's now give this to
4947 // the target.
4948
Joe Onorato8a9b2202010-02-26 18:56:32 -08004949 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004950 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 HashMap<Uri, UriPermission> targetUris
4953 = mGrantedUriPermissions.get(targetUid);
4954 if (targetUris == null) {
4955 targetUris = new HashMap<Uri, UriPermission>();
4956 mGrantedUriPermissions.put(targetUid, targetUris);
4957 }
4958
4959 UriPermission perm = targetUris.get(uri);
4960 if (perm == null) {
4961 perm = new UriPermission(targetUid, uri);
4962 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004966 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004968 } else {
4969 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4970 perm.readOwners.add(owner);
4971 owner.addReadPermission(perm);
4972 }
4973 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4974 perm.writeOwners.add(owner);
4975 owner.addWritePermission(perm);
4976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978 }
4979
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004980 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4981 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004982 if (targetPkg == null) {
4983 throw new NullPointerException("targetPkg");
4984 }
4985
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004986 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004987 if (targetUid < 0) {
4988 return;
4989 }
4990
4991 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4992 }
4993
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004994 static class NeededUriGrants extends ArrayList<Uri> {
4995 final String targetPkg;
4996 final int targetUid;
4997 final int flags;
4998
4999 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5000 targetPkg = _targetPkg;
5001 targetUid = _targetUid;
5002 flags = _flags;
5003 }
5004 }
5005
Dianne Hackborn39792d22010-08-19 18:01:52 -07005006 /**
5007 * Like checkGrantUriPermissionLocked, but takes an Intent.
5008 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005009 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5010 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005011 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005012 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5013 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005014 + " from " + intent + "; flags=0x"
5015 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5016
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005017 if (targetPkg == null) {
5018 throw new NullPointerException("targetPkg");
5019 }
5020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005022 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 }
5024 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005025 ClipData clip = intent.getClipData();
5026 if (data == null && clip == null) {
5027 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005028 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005029 if (data != null) {
5030 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5031 mode, needed != null ? needed.targetUid : -1);
5032 if (target > 0) {
5033 if (needed == null) {
5034 needed = new NeededUriGrants(targetPkg, target, mode);
5035 }
5036 needed.add(data);
5037 }
5038 }
5039 if (clip != null) {
5040 for (int i=0; i<clip.getItemCount(); i++) {
5041 Uri uri = clip.getItemAt(i).getUri();
5042 if (uri != null) {
5043 int target = -1;
5044 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5045 mode, needed != null ? needed.targetUid : -1);
5046 if (target > 0) {
5047 if (needed == null) {
5048 needed = new NeededUriGrants(targetPkg, target, mode);
5049 }
5050 needed.add(uri);
5051 }
5052 } else {
5053 Intent clipIntent = clip.getItemAt(i).getIntent();
5054 if (clipIntent != null) {
5055 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5056 callingUid, targetPkg, clipIntent, mode, needed);
5057 if (newNeeded != null) {
5058 needed = newNeeded;
5059 }
5060 }
5061 }
5062 }
5063 }
5064
5065 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005066 }
5067
5068 /**
5069 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5070 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005071 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5072 UriPermissionOwner owner) {
5073 if (needed != null) {
5074 for (int i=0; i<needed.size(); i++) {
5075 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5076 needed.get(i), needed.flags, owner);
5077 }
5078 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005079 }
5080
5081 void grantUriPermissionFromIntentLocked(int callingUid,
5082 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005083 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005084 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005085 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 return;
5087 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005088
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005089 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 }
5091
5092 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5093 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005094 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 synchronized(this) {
5096 final ProcessRecord r = getRecordForAppLocked(caller);
5097 if (r == null) {
5098 throw new SecurityException("Unable to find app for caller "
5099 + caller
5100 + " when granting permission to uri " + uri);
5101 }
5102 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005103 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 }
5105 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005106 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 }
5108
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005109 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 null);
5111 }
5112 }
5113
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005114 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5116 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5117 HashMap<Uri, UriPermission> perms
5118 = mGrantedUriPermissions.get(perm.uid);
5119 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005120 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005121 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005122 perms.remove(perm.uri);
5123 if (perms.size() == 0) {
5124 mGrantedUriPermissions.remove(perm.uid);
5125 }
5126 }
5127 }
5128 }
5129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5131 int modeFlags) {
5132 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5133 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5134 if (modeFlags == 0) {
5135 return;
5136 }
5137
Joe Onorato8a9b2202010-02-26 18:56:32 -08005138 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005139 "Revoking all granted permissions to " + uri);
5140
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005141 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142
5143 final String authority = uri.getAuthority();
5144 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005145 int userId = UserId.getUserId(callingUid);
5146 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147 if (cpr != null) {
5148 pi = cpr.info;
5149 } else {
5150 try {
5151 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005152 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 } catch (RemoteException ex) {
5154 }
5155 }
5156 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005157 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 return;
5159 }
5160
5161 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005162 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 // Right now, if you are not the original owner of the permission,
5164 // you are not allowed to revoke it.
5165 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5166 throw new SecurityException("Uid " + callingUid
5167 + " does not have permission to uri " + uri);
5168 //}
5169 }
5170
5171 // Go through all of the permissions and remove any that match.
5172 final List<String> SEGMENTS = uri.getPathSegments();
5173 if (SEGMENTS != null) {
5174 final int NS = SEGMENTS.size();
5175 int N = mGrantedUriPermissions.size();
5176 for (int i=0; i<N; i++) {
5177 HashMap<Uri, UriPermission> perms
5178 = mGrantedUriPermissions.valueAt(i);
5179 Iterator<UriPermission> it = perms.values().iterator();
5180 toploop:
5181 while (it.hasNext()) {
5182 UriPermission perm = it.next();
5183 Uri targetUri = perm.uri;
5184 if (!authority.equals(targetUri.getAuthority())) {
5185 continue;
5186 }
5187 List<String> targetSegments = targetUri.getPathSegments();
5188 if (targetSegments == null) {
5189 continue;
5190 }
5191 if (targetSegments.size() < NS) {
5192 continue;
5193 }
5194 for (int j=0; j<NS; j++) {
5195 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5196 continue toploop;
5197 }
5198 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005199 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005200 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 perm.clearModes(modeFlags);
5202 if (perm.modeFlags == 0) {
5203 it.remove();
5204 }
5205 }
5206 if (perms.size() == 0) {
5207 mGrantedUriPermissions.remove(
5208 mGrantedUriPermissions.keyAt(i));
5209 N--;
5210 i--;
5211 }
5212 }
5213 }
5214 }
5215
5216 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5217 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005218 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 synchronized(this) {
5220 final ProcessRecord r = getRecordForAppLocked(caller);
5221 if (r == null) {
5222 throw new SecurityException("Unable to find app for caller "
5223 + caller
5224 + " when revoking permission to uri " + uri);
5225 }
5226 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005227 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 return;
5229 }
5230
5231 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5232 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5233 if (modeFlags == 0) {
5234 return;
5235 }
5236
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005237 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238
5239 final String authority = uri.getAuthority();
5240 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005241 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 if (cpr != null) {
5243 pi = cpr.info;
5244 } else {
5245 try {
5246 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005247 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 } catch (RemoteException ex) {
5249 }
5250 }
5251 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005252 Slog.w(TAG, "No content provider found for permission revoke: "
5253 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 return;
5255 }
5256
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005257 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 }
5259 }
5260
Dianne Hackborn7e269642010-08-25 19:50:20 -07005261 @Override
5262 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005263 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005264 synchronized(this) {
5265 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5266 return owner.getExternalTokenLocked();
5267 }
5268 }
5269
5270 @Override
5271 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5272 Uri uri, int modeFlags) {
5273 synchronized(this) {
5274 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5275 if (owner == null) {
5276 throw new IllegalArgumentException("Unknown owner: " + token);
5277 }
5278 if (fromUid != Binder.getCallingUid()) {
5279 if (Binder.getCallingUid() != Process.myUid()) {
5280 // Only system code can grant URI permissions on behalf
5281 // of other users.
5282 throw new SecurityException("nice try");
5283 }
5284 }
5285 if (targetPkg == null) {
5286 throw new IllegalArgumentException("null target");
5287 }
5288 if (uri == null) {
5289 throw new IllegalArgumentException("null uri");
5290 }
5291
5292 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5293 }
5294 }
5295
5296 @Override
5297 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5298 synchronized(this) {
5299 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5300 if (owner == null) {
5301 throw new IllegalArgumentException("Unknown owner: " + token);
5302 }
5303
5304 if (uri == null) {
5305 owner.removeUriPermissionsLocked(mode);
5306 } else {
5307 owner.removeUriPermissionLocked(uri, mode);
5308 }
5309 }
5310 }
5311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5313 synchronized (this) {
5314 ProcessRecord app =
5315 who != null ? getRecordForAppLocked(who) : null;
5316 if (app == null) return;
5317
5318 Message msg = Message.obtain();
5319 msg.what = WAIT_FOR_DEBUGGER_MSG;
5320 msg.obj = app;
5321 msg.arg1 = waiting ? 1 : 0;
5322 mHandler.sendMessage(msg);
5323 }
5324 }
5325
5326 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005327 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5328 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005330 outInfo.threshold = homeAppMem;
5331 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5332 outInfo.hiddenAppThreshold = hiddenAppMem;
5333 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005334 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005335 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5336 ProcessList.VISIBLE_APP_ADJ);
5337 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5338 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005339 }
5340
5341 // =========================================================
5342 // TASK MANAGEMENT
5343 // =========================================================
5344
5345 public List getTasks(int maxNum, int flags,
5346 IThumbnailReceiver receiver) {
5347 ArrayList list = new ArrayList();
5348
5349 PendingThumbnailsRecord pending = null;
5350 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005351 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352
5353 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005354 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5356 + ", receiver=" + receiver);
5357
5358 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5359 != PackageManager.PERMISSION_GRANTED) {
5360 if (receiver != null) {
5361 // If the caller wants to wait for pending thumbnails,
5362 // it ain't gonna get them.
5363 try {
5364 receiver.finished();
5365 } catch (RemoteException ex) {
5366 }
5367 }
5368 String msg = "Permission Denial: getTasks() from pid="
5369 + Binder.getCallingPid()
5370 + ", uid=" + Binder.getCallingUid()
5371 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005372 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005373 throw new SecurityException(msg);
5374 }
5375
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005376 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005377 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005378 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005379 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 TaskRecord curTask = null;
5381 int numActivities = 0;
5382 int numRunning = 0;
5383 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005384 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005386 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387
5388 // Initialize state for next task if needed.
5389 if (top == null ||
5390 (top.state == ActivityState.INITIALIZING
5391 && top.task == r.task)) {
5392 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 curTask = r.task;
5394 numActivities = numRunning = 0;
5395 }
5396
5397 // Add 'r' into the current task.
5398 numActivities++;
5399 if (r.app != null && r.app.thread != null) {
5400 numRunning++;
5401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402
Joe Onorato8a9b2202010-02-26 18:56:32 -08005403 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 TAG, r.intent.getComponent().flattenToShortString()
5405 + ": task=" + r.task);
5406
5407 // If the next one is a different task, generate a new
5408 // TaskInfo entry for what we have.
5409 if (next == null || next.task != curTask) {
5410 ActivityManager.RunningTaskInfo ci
5411 = new ActivityManager.RunningTaskInfo();
5412 ci.id = curTask.taskId;
5413 ci.baseActivity = r.intent.getComponent();
5414 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005415 if (top.thumbHolder != null) {
5416 ci.description = top.thumbHolder.lastDescription;
5417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 ci.numActivities = numActivities;
5419 ci.numRunning = numRunning;
5420 //System.out.println(
5421 // "#" + maxNum + ": " + " descr=" + ci.description);
5422 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005423 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 TAG, "State=" + top.state + "Idle=" + top.idle
5425 + " app=" + top.app
5426 + " thr=" + (top.app != null ? top.app.thread : null));
5427 if (top.state == ActivityState.RESUMED
5428 || top.state == ActivityState.PAUSING) {
5429 if (top.idle && top.app != null
5430 && top.app.thread != null) {
5431 topRecord = top;
5432 topThumbnail = top.app.thread;
5433 } else {
5434 top.thumbnailNeeded = true;
5435 }
5436 }
5437 if (pending == null) {
5438 pending = new PendingThumbnailsRecord(receiver);
5439 }
5440 pending.pendingRecords.add(top);
5441 }
5442 list.add(ci);
5443 maxNum--;
5444 top = null;
5445 }
5446 }
5447
5448 if (pending != null) {
5449 mPendingThumbnails.add(pending);
5450 }
5451 }
5452
Joe Onorato8a9b2202010-02-26 18:56:32 -08005453 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454
5455 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005456 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005458 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005460 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005461 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 }
5463 }
5464
5465 if (pending == null && receiver != null) {
5466 // In this case all thumbnails were available and the client
5467 // is being asked to be told when the remaining ones come in...
5468 // which is unusually, since the top-most currently running
5469 // activity should never have a canned thumbnail! Oh well.
5470 try {
5471 receiver.finished();
5472 } catch (RemoteException ex) {
5473 }
5474 }
5475
5476 return list;
5477 }
5478
5479 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5480 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005481 final int callingUid = Binder.getCallingUid();
5482 // If it's the system uid asking, then use the current user id.
5483 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5484 // require the entire list.
5485 final int callingUserId = callingUid == Process.SYSTEM_UID
5486 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 synchronized (this) {
5488 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5489 "getRecentTasks()");
5490
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005491 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 final int N = mRecentTasks.size();
5494 ArrayList<ActivityManager.RecentTaskInfo> res
5495 = new ArrayList<ActivityManager.RecentTaskInfo>(
5496 maxNum < N ? maxNum : N);
5497 for (int i=0; i<N && maxNum > 0; i++) {
5498 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005499 // Only add calling user's recent tasks
5500 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005501 // Return the entry if desired by the caller. We always return
5502 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005503 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005504 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5505 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005506
Dianne Hackborn905577f2011-09-07 18:31:28 -07005507 if (i == 0
5508 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 || (tr.intent == null)
5510 || ((tr.intent.getFlags()
5511 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5512 ActivityManager.RecentTaskInfo rti
5513 = new ActivityManager.RecentTaskInfo();
5514 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005515 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 rti.baseIntent = new Intent(
5517 tr.intent != null ? tr.intent : tr.affinityIntent);
5518 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005519 rti.description = tr.lastDescription;
5520
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005521 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5522 // Check whether this activity is currently available.
5523 try {
5524 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005525 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5526 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005527 continue;
5528 }
5529 } else if (rti.baseIntent != null) {
5530 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005531 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005532 continue;
5533 }
5534 }
5535 } catch (RemoteException e) {
5536 // Will never happen.
5537 }
5538 }
5539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 res.add(rti);
5541 maxNum--;
5542 }
5543 }
5544 return res;
5545 }
5546 }
5547
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005548 private TaskRecord taskForIdLocked(int id) {
5549 final int N = mRecentTasks.size();
5550 for (int i=0; i<N; i++) {
5551 TaskRecord tr = mRecentTasks.get(i);
5552 if (tr.taskId == id) {
5553 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005554 }
5555 }
5556 return null;
5557 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005558
5559 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5560 synchronized (this) {
5561 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5562 "getTaskThumbnails()");
5563 TaskRecord tr = taskForIdLocked(id);
5564 if (tr != null) {
5565 return mMainStack.getTaskThumbnailsLocked(tr);
5566 }
5567 }
5568 return null;
5569 }
5570
5571 public boolean removeSubTask(int taskId, int subTaskIndex) {
5572 synchronized (this) {
5573 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5574 "removeSubTask()");
5575 long ident = Binder.clearCallingIdentity();
5576 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005577 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5578 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005579 } finally {
5580 Binder.restoreCallingIdentity(ident);
5581 }
5582 }
5583 }
5584
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005585 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5586 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005587 Intent baseIntent = new Intent(
5588 tr.intent != null ? tr.intent : tr.affinityIntent);
5589 ComponentName component = baseIntent.getComponent();
5590 if (component == null) {
5591 Slog.w(TAG, "Now component for base intent of task: " + tr);
5592 return;
5593 }
5594
5595 // Find any running services associated with this app.
5596 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005597 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005598 if (sr.packageName.equals(component.getPackageName())) {
5599 services.add(sr);
5600 }
5601 }
5602
5603 // Take care of any running services associated with the app.
5604 for (int i=0; i<services.size(); i++) {
5605 ServiceRecord sr = services.get(i);
5606 if (sr.startRequested) {
5607 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005608 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005609 stopServiceLocked(sr);
5610 } else {
5611 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005612 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005613 if (sr.app != null && sr.app.thread != null) {
5614 sendServiceArgsLocked(sr, false);
5615 }
5616 }
5617 }
5618 }
5619
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005620 if (killProcesses) {
5621 // Find any running processes associated with this app.
5622 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5623 SparseArray<ProcessRecord> appProcs
5624 = mProcessNames.getMap().get(component.getPackageName());
5625 if (appProcs != null) {
5626 for (int i=0; i<appProcs.size(); i++) {
5627 procs.add(appProcs.valueAt(i));
5628 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005629 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005630
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005631 // Kill the running processes.
5632 for (int i=0; i<procs.size(); i++) {
5633 ProcessRecord pr = procs.get(i);
5634 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5635 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5636 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5637 pr.processName, pr.setAdj, "remove task");
5638 Process.killProcessQuiet(pr.pid);
5639 } else {
5640 pr.waitingToKill = "remove task";
5641 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005642 }
5643 }
5644 }
5645
5646 public boolean removeTask(int taskId, int flags) {
5647 synchronized (this) {
5648 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5649 "removeTask()");
5650 long ident = Binder.clearCallingIdentity();
5651 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005652 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5653 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005654 if (r != null) {
5655 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005656 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005657 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005658 } else {
5659 TaskRecord tr = null;
5660 int i=0;
5661 while (i < mRecentTasks.size()) {
5662 TaskRecord t = mRecentTasks.get(i);
5663 if (t.taskId == taskId) {
5664 tr = t;
5665 break;
5666 }
5667 i++;
5668 }
5669 if (tr != null) {
5670 if (tr.numActivities <= 0) {
5671 // Caller is just removing a recent task that is
5672 // not actively running. That is easy!
5673 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005674 cleanUpRemovedTaskLocked(tr, flags);
5675 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005676 } else {
5677 Slog.w(TAG, "removeTask: task " + taskId
5678 + " does not have activities to remove, "
5679 + " but numActivities=" + tr.numActivities
5680 + ": " + tr);
5681 }
5682 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005683 }
5684 } finally {
5685 Binder.restoreCallingIdentity(ident);
5686 }
5687 }
5688 return false;
5689 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5692 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005693 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 TaskRecord jt = startTask;
5695
5696 // First look backwards
5697 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005698 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 if (r.task != jt) {
5700 jt = r.task;
5701 if (affinity.equals(jt.affinity)) {
5702 return j;
5703 }
5704 }
5705 }
5706
5707 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005708 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 jt = startTask;
5710 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005711 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 if (r.task != jt) {
5713 if (affinity.equals(jt.affinity)) {
5714 return j;
5715 }
5716 jt = r.task;
5717 }
5718 }
5719
5720 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005721 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 return N-1;
5723 }
5724
5725 return -1;
5726 }
5727
5728 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005729 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005731 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5733 "moveTaskToFront()");
5734
5735 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005736 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5737 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005738 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005739 return;
5740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 final long origId = Binder.clearCallingIdentity();
5742 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005743 TaskRecord tr = taskForIdLocked(task);
5744 if (tr != null) {
5745 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5746 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005748 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5749 // Caller wants the home activity moved with it. To accomplish this,
5750 // we'll just move the home task to the top first.
5751 mMainStack.moveHomeToFrontLocked();
5752 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005753 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005754 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005756 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5757 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005759 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5760 mMainStack.mUserLeaving = true;
5761 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005762 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5763 // Caller wants the home activity moved with it. To accomplish this,
5764 // we'll just move the home task to the top first.
5765 mMainStack.moveHomeToFrontLocked();
5766 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005767 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 return;
5769 }
5770 }
5771 } finally {
5772 Binder.restoreCallingIdentity(origId);
5773 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005774 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 }
5776 }
5777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 public void moveTaskToBack(int task) {
5779 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5780 "moveTaskToBack()");
5781
5782 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005783 if (mMainStack.mResumedActivity != null
5784 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005785 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5786 Binder.getCallingUid(), "Task to back")) {
5787 return;
5788 }
5789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005791 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 Binder.restoreCallingIdentity(origId);
5793 }
5794 }
5795
5796 /**
5797 * Moves an activity, and all of the other activities within the same task, to the bottom
5798 * of the history stack. The activity's order within the task is unchanged.
5799 *
5800 * @param token A reference to the activity we wish to move
5801 * @param nonRoot If false then this only works if the activity is the root
5802 * of a task; if true it will work for any activity in a task.
5803 * @return Returns true if the move completed, false if not.
5804 */
5805 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005806 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 synchronized(this) {
5808 final long origId = Binder.clearCallingIdentity();
5809 int taskId = getTaskForActivityLocked(token, !nonRoot);
5810 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005811 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 }
5813 Binder.restoreCallingIdentity(origId);
5814 }
5815 return false;
5816 }
5817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 public void moveTaskBackwards(int task) {
5819 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5820 "moveTaskBackwards()");
5821
5822 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005823 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5824 Binder.getCallingUid(), "Task backwards")) {
5825 return;
5826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 final long origId = Binder.clearCallingIdentity();
5828 moveTaskBackwardsLocked(task);
5829 Binder.restoreCallingIdentity(origId);
5830 }
5831 }
5832
5833 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005834 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
5836
5837 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5838 synchronized(this) {
5839 return getTaskForActivityLocked(token, onlyRoot);
5840 }
5841 }
5842
5843 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005844 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 TaskRecord lastTask = null;
5846 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005847 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005848 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 if (!onlyRoot || lastTask != r.task) {
5850 return r.task.taskId;
5851 }
5852 return -1;
5853 }
5854 lastTask = r.task;
5855 }
5856
5857 return -1;
5858 }
5859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 // =========================================================
5861 // THUMBNAILS
5862 // =========================================================
5863
5864 public void reportThumbnail(IBinder token,
5865 Bitmap thumbnail, CharSequence description) {
5866 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5867 final long origId = Binder.clearCallingIdentity();
5868 sendPendingThumbnail(null, token, thumbnail, description, true);
5869 Binder.restoreCallingIdentity(origId);
5870 }
5871
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005872 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 Bitmap thumbnail, CharSequence description, boolean always) {
5874 TaskRecord task = null;
5875 ArrayList receivers = null;
5876
5877 //System.out.println("Send pending thumbnail: " + r);
5878
5879 synchronized(this) {
5880 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005881 r = mMainStack.isInStackLocked(token);
5882 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 return;
5884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005886 if (thumbnail == null && r.thumbHolder != null) {
5887 thumbnail = r.thumbHolder.lastThumbnail;
5888 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 }
5890 if (thumbnail == null && !always) {
5891 // If there is no thumbnail, and this entry is not actually
5892 // going away, then abort for now and pick up the next
5893 // thumbnail we get.
5894 return;
5895 }
5896 task = r.task;
5897
5898 int N = mPendingThumbnails.size();
5899 int i=0;
5900 while (i<N) {
5901 PendingThumbnailsRecord pr =
5902 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5903 //System.out.println("Looking in " + pr.pendingRecords);
5904 if (pr.pendingRecords.remove(r)) {
5905 if (receivers == null) {
5906 receivers = new ArrayList();
5907 }
5908 receivers.add(pr);
5909 if (pr.pendingRecords.size() == 0) {
5910 pr.finished = true;
5911 mPendingThumbnails.remove(i);
5912 N--;
5913 continue;
5914 }
5915 }
5916 i++;
5917 }
5918 }
5919
5920 if (receivers != null) {
5921 final int N = receivers.size();
5922 for (int i=0; i<N; i++) {
5923 try {
5924 PendingThumbnailsRecord pr =
5925 (PendingThumbnailsRecord)receivers.get(i);
5926 pr.receiver.newThumbnail(
5927 task != null ? task.taskId : -1, thumbnail, description);
5928 if (pr.finished) {
5929 pr.receiver.finished();
5930 }
5931 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005932 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 }
5934 }
5935 }
5936 }
5937
5938 // =========================================================
5939 // CONTENT PROVIDERS
5940 // =========================================================
5941
Jeff Brown10e89712011-07-08 18:52:57 -07005942 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5943 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005945 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005946 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005947 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 } catch (RemoteException ex) {
5949 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005950 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005951 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5952 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005953 if (providers != null) {
5954 final int N = providers.size();
5955 for (int i=0; i<N; i++) {
5956 ProviderInfo cpi =
5957 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005958
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005959 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005960 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005962 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005963 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005965 if (DEBUG_MU)
5966 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 app.pubProviders.put(cpi.name, cpr);
5968 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005969 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 }
5971 }
5972 return providers;
5973 }
5974
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005975 /**
5976 * Check if {@link ProcessRecord} has a possible chance at accessing the
5977 * given {@link ProviderInfo}. Final permission checking is always done
5978 * in {@link ContentProvider}.
5979 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005981 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005983 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005985 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005986 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 return null;
5988 }
5989 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005990 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 == PackageManager.PERMISSION_GRANTED) {
5992 return null;
5993 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005994
5995 PathPermission[] pps = cpi.pathPermissions;
5996 if (pps != null) {
5997 int i = pps.length;
5998 while (i > 0) {
5999 i--;
6000 PathPermission pp = pps[i];
6001 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006002 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006003 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006004 return null;
6005 }
6006 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006007 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006008 == PackageManager.PERMISSION_GRANTED) {
6009 return null;
6010 }
6011 }
6012 }
6013
Dianne Hackbornb424b632010-08-18 15:59:05 -07006014 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6015 if (perms != null) {
6016 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6017 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6018 return null;
6019 }
6020 }
6021 }
6022
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006023 String msg;
6024 if (!cpi.exported) {
6025 msg = "Permission Denial: opening provider " + cpi.name
6026 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6027 + ", uid=" + callingUid + ") that is not exported from uid "
6028 + cpi.applicationInfo.uid;
6029 } else {
6030 msg = "Permission Denial: opening provider " + cpi.name
6031 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6032 + ", uid=" + callingUid + ") requires "
6033 + cpi.readPermission + " or " + cpi.writePermission;
6034 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006035 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 return msg;
6037 }
6038
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006039 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6040 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006041 if (r != null) {
6042 Integer cnt = r.conProviders.get(cpr);
6043 if (DEBUG_PROVIDER) Slog.v(TAG,
6044 "Adding provider requested by "
6045 + r.processName + " from process "
6046 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6047 + " cnt=" + (cnt == null ? 1 : cnt));
6048 if (cnt == null) {
6049 cpr.clients.add(r);
6050 r.conProviders.put(cpr, new Integer(1));
6051 return true;
6052 } else {
6053 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6054 }
6055 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006056 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006057 }
6058 return false;
6059 }
6060
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006061 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6062 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006063 if (r != null) {
6064 Integer cnt = r.conProviders.get(cpr);
6065 if (DEBUG_PROVIDER) Slog.v(TAG,
6066 "Removing provider requested by "
6067 + r.processName + " from process "
6068 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6069 + " cnt=" + cnt);
6070 if (cnt == null || cnt.intValue() <= 1) {
6071 cpr.clients.remove(r);
6072 r.conProviders.remove(cpr);
6073 return true;
6074 } else {
6075 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6076 }
6077 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006078 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006079 }
6080 return false;
6081 }
6082
Amith Yamasani742a6712011-05-04 14:49:28 -07006083 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006084 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 ContentProviderRecord cpr;
6086 ProviderInfo cpi = null;
6087
6088 synchronized(this) {
6089 ProcessRecord r = null;
6090 if (caller != null) {
6091 r = getRecordForAppLocked(caller);
6092 if (r == null) {
6093 throw new SecurityException(
6094 "Unable to find app for caller " + caller
6095 + " (pid=" + Binder.getCallingPid()
6096 + ") when getting content provider " + name);
6097 }
6098 }
6099
6100 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006101 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006102 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006103 boolean providerRunning = cpr != null;
6104 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006106 String msg;
6107 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6108 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 }
6110
6111 if (r != null && cpr.canRunHere(r)) {
6112 // This provider has been published or is in the process
6113 // of being published... but it is also allowed to run
6114 // in the caller's process, so don't make a connection
6115 // and just let the caller instantiate its own instance.
6116 if (cpr.provider != null) {
6117 // don't give caller the provider object, it needs
6118 // to make its own.
6119 cpr = new ContentProviderRecord(cpr);
6120 }
6121 return cpr;
6122 }
6123
6124 final long origId = Binder.clearCallingIdentity();
6125
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006126 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006128 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006129 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006130 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006131 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006132 // make sure to count it as being accessed and thus
6133 // back up on the LRU list. This is good because
6134 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006135 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006136 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006137 }
6138
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006139 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006140 if (false) {
6141 if (cpr.name.flattenToShortString().equals(
6142 "com.android.providers.calendar/.CalendarProvider2")) {
6143 Slog.v(TAG, "****************** KILLING "
6144 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006145 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006146 }
6147 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006148 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006149 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6150 // NOTE: there is still a race here where a signal could be
6151 // pending on the process even though we managed to update its
6152 // adj level. Not sure what to do about this, but at least
6153 // the race is now smaller.
6154 if (!success) {
6155 // Uh oh... it looks like the provider's process
6156 // has been killed on us. We need to wait for a new
6157 // process to be started, and make sure its death
6158 // doesn't kill our process.
6159 Slog.i(TAG,
6160 "Existing provider " + cpr.name.flattenToShortString()
6161 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006162 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006163 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006164 if (!lastRef) {
6165 // This wasn't the last ref our process had on
6166 // the provider... we have now been killed, bail.
6167 return null;
6168 }
6169 providerRunning = false;
6170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 }
6172
6173 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006176 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006178 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006179 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006180 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 } catch (RemoteException ex) {
6182 }
6183 if (cpi == null) {
6184 return null;
6185 }
6186
Amith Yamasani483f3b02012-03-13 16:08:00 -07006187 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006188
Dianne Hackbornb424b632010-08-18 15:59:05 -07006189 String msg;
6190 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6191 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 }
6193
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006194 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006195 && !cpi.processName.equals("system")) {
6196 // If this content provider does not run in the system
6197 // process, and the system is not yet ready to run other
6198 // processes, then fail fast instead of hanging.
6199 throw new IllegalArgumentException(
6200 "Attempt to launch content provider before system ready");
6201 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006202
6203 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006204 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 final boolean firstClass = cpr == null;
6206 if (firstClass) {
6207 try {
6208 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006209 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 getApplicationInfo(
6211 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006212 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006214 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 + cpi.name);
6216 return null;
6217 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006218 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006219 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 } catch (RemoteException ex) {
6221 // pm is in same process, this will never happen.
6222 }
6223 }
6224
6225 if (r != null && cpr.canRunHere(r)) {
6226 // If this is a multiprocess provider, then just return its
6227 // info and allow the caller to instantiate it. Only do
6228 // this if the provider is the same user as the caller's
6229 // process, or can run as root (so can be in any process).
6230 return cpr;
6231 }
6232
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006233 if (DEBUG_PROVIDER) {
6234 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006235 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006236 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 }
6238
6239 // This is single process, and our app is now connecting to it.
6240 // See if we are already in the process of launching this
6241 // provider.
6242 final int N = mLaunchingProviders.size();
6243 int i;
6244 for (i=0; i<N; i++) {
6245 if (mLaunchingProviders.get(i) == cpr) {
6246 break;
6247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 }
6249
6250 // If the provider is not already being launched, then get it
6251 // started.
6252 if (i >= N) {
6253 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006254
6255 try {
6256 // Content provider is now in use, its package can't be stopped.
6257 try {
6258 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006259 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006260 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006261 } catch (IllegalArgumentException e) {
6262 Slog.w(TAG, "Failed trying to unstop package "
6263 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006264 }
6265
6266 ProcessRecord proc = startProcessLocked(cpi.processName,
6267 cpr.appInfo, false, 0, "content provider",
6268 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006269 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006270 if (proc == null) {
6271 Slog.w(TAG, "Unable to launch app "
6272 + cpi.applicationInfo.packageName + "/"
6273 + cpi.applicationInfo.uid + " for provider "
6274 + name + ": process is bad");
6275 return null;
6276 }
6277 cpr.launchingApp = proc;
6278 mLaunchingProviders.add(cpr);
6279 } finally {
6280 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 }
6283
6284 // Make sure the provider is published (the same provider class
6285 // may be published under multiple names).
6286 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006287 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006289
Amith Yamasani742a6712011-05-04 14:49:28 -07006290 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006291 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
6293 }
6294
6295 // Wait for the provider to be published...
6296 synchronized (cpr) {
6297 while (cpr.provider == null) {
6298 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006299 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 + cpi.applicationInfo.packageName + "/"
6301 + cpi.applicationInfo.uid + " for provider "
6302 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006303 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 cpi.applicationInfo.packageName,
6305 cpi.applicationInfo.uid, name);
6306 return null;
6307 }
6308 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006309 if (DEBUG_MU) {
6310 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6311 + cpr.launchingApp);
6312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 cpr.wait();
6314 } catch (InterruptedException ex) {
6315 }
6316 }
6317 }
6318 return cpr;
6319 }
6320
6321 public final ContentProviderHolder getContentProvider(
6322 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006323 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 if (caller == null) {
6325 String msg = "null IApplicationThread when getting content provider "
6326 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006327 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 throw new SecurityException(msg);
6329 }
6330
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006331 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
6333
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006334 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6335 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6336 "Do not have permission in call getContentProviderExternal()");
6337 return getContentProviderExternalUnchecked(name, token);
6338 }
6339
6340 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6341 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 }
6343
6344 /**
6345 * Drop a content provider from a ProcessRecord's bookkeeping
6346 * @param cpr
6347 */
6348 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006349 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006351 int userId = UserId.getUserId(Binder.getCallingUid());
6352 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006354 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006355 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006356 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 return;
6358 }
6359 final ProcessRecord r = getRecordForAppLocked(caller);
6360 if (r == null) {
6361 throw new SecurityException(
6362 "Unable to find app for caller " + caller +
6363 " when removing content provider " + name);
6364 }
6365 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006366 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006367 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6368 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6369 + r.info.processName + " from process "
6370 + localCpr.appInfo.processName);
6371 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006373 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006374 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 return;
6376 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006377 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006378 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 }
6382 }
6383
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006384 public void removeContentProviderExternal(String name, IBinder token) {
6385 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6386 "Do not have permission in call removeContentProviderExternal()");
6387 removeContentProviderExternalUnchecked(name, token);
6388 }
6389
6390 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006392 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6393 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 if(cpr == null) {
6395 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006396 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 return;
6398 }
6399
6400 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006401 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006402 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6403 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006404 if (localCpr.hasExternalProcessHandles()) {
6405 if (localCpr.removeExternalProcessHandleLocked(token)) {
6406 updateOomAdjLocked();
6407 } else {
6408 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6409 + " with no external reference for token: "
6410 + token + ".");
6411 }
6412 } else {
6413 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6414 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 }
6417 }
6418
6419 public final void publishContentProviders(IApplicationThread caller,
6420 List<ContentProviderHolder> providers) {
6421 if (providers == null) {
6422 return;
6423 }
6424
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006425 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 synchronized(this) {
6427 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006428 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006429 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 if (r == null) {
6431 throw new SecurityException(
6432 "Unable to find app for caller " + caller
6433 + " (pid=" + Binder.getCallingPid()
6434 + ") when publishing content providers");
6435 }
6436
6437 final long origId = Binder.clearCallingIdentity();
6438
6439 final int N = providers.size();
6440 for (int i=0; i<N; i++) {
6441 ContentProviderHolder src = providers.get(i);
6442 if (src == null || src.info == null || src.provider == null) {
6443 continue;
6444 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006445 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006446 if (DEBUG_MU)
6447 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006449 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006450 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 String names[] = dst.info.authority.split(";");
6452 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006453 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
6455
6456 int NL = mLaunchingProviders.size();
6457 int j;
6458 for (j=0; j<NL; j++) {
6459 if (mLaunchingProviders.get(j) == dst) {
6460 mLaunchingProviders.remove(j);
6461 j--;
6462 NL--;
6463 }
6464 }
6465 synchronized (dst) {
6466 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006467 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 dst.notifyAll();
6469 }
6470 updateOomAdjLocked(r);
6471 }
6472 }
6473
6474 Binder.restoreCallingIdentity(origId);
6475 }
6476 }
6477
6478 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006479 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006480 synchronized (mSelf) {
6481 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6482 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006483 if (providers != null) {
6484 for (int i=providers.size()-1; i>=0; i--) {
6485 ProviderInfo pi = (ProviderInfo)providers.get(i);
6486 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6487 Slog.w(TAG, "Not installing system proc provider " + pi.name
6488 + ": not system .apk");
6489 providers.remove(i);
6490 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006491 }
6492 }
6493 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006494 if (providers != null) {
6495 mSystemThread.installSystemProviders(providers);
6496 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006497
6498 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006499
6500 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 }
6502
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006503 /**
6504 * Allows app to retrieve the MIME type of a URI without having permission
6505 * to access its content provider.
6506 *
6507 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6508 *
6509 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6510 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6511 */
6512 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006513 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006514 final String name = uri.getAuthority();
6515 final long ident = Binder.clearCallingIdentity();
6516 ContentProviderHolder holder = null;
6517
6518 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006519 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006520 if (holder != null) {
6521 return holder.provider.getType(uri);
6522 }
6523 } catch (RemoteException e) {
6524 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6525 return null;
6526 } finally {
6527 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006528 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006529 }
6530 Binder.restoreCallingIdentity(ident);
6531 }
6532
6533 return null;
6534 }
6535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 // =========================================================
6537 // GLOBAL MANAGEMENT
6538 // =========================================================
6539
6540 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006541 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 String proc = customProcess != null ? customProcess : info.processName;
6543 BatteryStatsImpl.Uid.Proc ps = null;
6544 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006545 int uid = info.uid;
6546 if (isolated) {
6547 int userId = UserId.getUserId(uid);
6548 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6549 uid = 0;
6550 while (true) {
6551 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6552 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6553 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6554 }
6555 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6556 mNextIsolatedProcessUid++;
6557 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6558 // No process for this uid, use it.
6559 break;
6560 }
6561 stepsLeft--;
6562 if (stepsLeft <= 0) {
6563 return null;
6564 }
6565 }
6566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 synchronized (stats) {
6568 ps = stats.getProcessStatsLocked(info.uid, proc);
6569 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006570 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 }
6572
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006573 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6574 ProcessRecord app;
6575 if (!isolated) {
6576 app = getProcessRecordLocked(info.processName, info.uid);
6577 } else {
6578 app = null;
6579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580
6581 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006582 app = newProcessRecordLocked(null, info, null, isolated);
6583 mProcessNames.put(info.processName, app.uid, app);
6584 if (isolated) {
6585 mIsolatedProcesses.put(app.uid, app);
6586 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006587 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 }
6589
Dianne Hackborne7f97212011-02-24 14:40:20 -08006590 // This package really, really can not be stopped.
6591 try {
6592 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006593 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006594 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006595 } catch (IllegalArgumentException e) {
6596 Slog.w(TAG, "Failed trying to unstop package "
6597 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006598 }
6599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6601 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6602 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006603 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 }
6605 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6606 mPersistentStartingProcesses.add(app);
6607 startProcessLocked(app, "added application", app.processName);
6608 }
6609
6610 return app;
6611 }
6612
6613 public void unhandledBack() {
6614 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6615 "unhandledBack()");
6616
6617 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006618 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006619 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 TAG, "Performing unhandledBack(): stack size = " + count);
6621 if (count > 1) {
6622 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006623 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6625 Binder.restoreCallingIdentity(origId);
6626 }
6627 }
6628 }
6629
6630 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006631 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006633 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 ParcelFileDescriptor pfd = null;
6635 if (cph != null) {
6636 // We record the binder invoker's uid in thread-local storage before
6637 // going to the content provider to open the file. Later, in the code
6638 // that handles all permissions checks, we look for this uid and use
6639 // that rather than the Activity Manager's own uid. The effect is that
6640 // we do the check against the caller's permissions even though it looks
6641 // to the content provider like the Activity Manager itself is making
6642 // the request.
6643 sCallerIdentity.set(new Identity(
6644 Binder.getCallingPid(), Binder.getCallingUid()));
6645 try {
6646 pfd = cph.provider.openFile(uri, "r");
6647 } catch (FileNotFoundException e) {
6648 // do nothing; pfd will be returned null
6649 } finally {
6650 // Ensure that whatever happens, we clean up the identity state
6651 sCallerIdentity.remove();
6652 }
6653
6654 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006655 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006657 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 }
6659 return pfd;
6660 }
6661
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006662 // Actually is sleeping or shutting down or whatever else in the future
6663 // is an inactive state.
6664 public boolean isSleeping() {
6665 return mSleeping || mShuttingDown;
6666 }
6667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006669 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6670 != PackageManager.PERMISSION_GRANTED) {
6671 throw new SecurityException("Requires permission "
6672 + android.Manifest.permission.DEVICE_POWER);
6673 }
6674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006676 mWentToSleep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 mWindowManager.setEventDispatching(false);
6678
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006679 if (!mSleeping) {
6680 mSleeping = true;
6681 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006682
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006683 // Initialize the wake times of all processes.
6684 checkExcessivePowerUsageLocked(false);
6685 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6686 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6687 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 }
6690 }
6691
Dianne Hackborn55280a92009-05-07 15:53:46 -07006692 public boolean shutdown(int timeout) {
6693 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6694 != PackageManager.PERMISSION_GRANTED) {
6695 throw new SecurityException("Requires permission "
6696 + android.Manifest.permission.SHUTDOWN);
6697 }
6698
6699 boolean timedout = false;
6700
6701 synchronized(this) {
6702 mShuttingDown = true;
6703 mWindowManager.setEventDispatching(false);
6704
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006705 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006706 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006707 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006708 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006709 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006710 long delay = endTime - System.currentTimeMillis();
6711 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006712 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006713 timedout = true;
6714 break;
6715 }
6716 try {
6717 this.wait();
6718 } catch (InterruptedException e) {
6719 }
6720 }
6721 }
6722 }
6723
6724 mUsageStatsService.shutdown();
6725 mBatteryStatsService.shutdown();
6726
6727 return timedout;
6728 }
6729
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006730 public final void activitySlept(IBinder token) {
6731 if (localLOGV) Slog.v(
6732 TAG, "Activity slept: token=" + token);
6733
6734 ActivityRecord r = null;
6735
6736 final long origId = Binder.clearCallingIdentity();
6737
6738 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006739 r = mMainStack.isInStackLocked(token);
6740 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006741 mMainStack.activitySleptLocked(r);
6742 }
6743 }
6744
6745 Binder.restoreCallingIdentity(origId);
6746 }
6747
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006748 private void comeOutOfSleepIfNeededLocked() {
6749 if (!mWentToSleep && !mLockScreenShown) {
6750 if (mSleeping) {
6751 mSleeping = false;
6752 mMainStack.awakeFromSleepingLocked();
6753 mMainStack.resumeTopActivityLocked(null);
6754 }
6755 }
6756 }
6757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006759 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6760 != PackageManager.PERMISSION_GRANTED) {
6761 throw new SecurityException("Requires permission "
6762 + android.Manifest.permission.DEVICE_POWER);
6763 }
6764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006766 mWentToSleep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 mWindowManager.setEventDispatching(true);
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006768 comeOutOfSleepIfNeededLocked();
6769 }
6770 }
6771
6772 public void setLockScreenShown(boolean shown) {
6773 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6774 != PackageManager.PERMISSION_GRANTED) {
6775 throw new SecurityException("Requires permission "
6776 + android.Manifest.permission.DEVICE_POWER);
6777 }
6778
6779 synchronized(this) {
6780 mLockScreenShown = shown;
6781 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 }
6783 }
6784
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006785 public void stopAppSwitches() {
6786 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6787 != PackageManager.PERMISSION_GRANTED) {
6788 throw new SecurityException("Requires permission "
6789 + android.Manifest.permission.STOP_APP_SWITCHES);
6790 }
6791
6792 synchronized(this) {
6793 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6794 + APP_SWITCH_DELAY_TIME;
6795 mDidAppSwitch = false;
6796 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6797 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6798 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6799 }
6800 }
6801
6802 public void resumeAppSwitches() {
6803 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6804 != PackageManager.PERMISSION_GRANTED) {
6805 throw new SecurityException("Requires permission "
6806 + android.Manifest.permission.STOP_APP_SWITCHES);
6807 }
6808
6809 synchronized(this) {
6810 // Note that we don't execute any pending app switches... we will
6811 // let those wait until either the timeout, or the next start
6812 // activity request.
6813 mAppSwitchesAllowedTime = 0;
6814 }
6815 }
6816
6817 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6818 String name) {
6819 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6820 return true;
6821 }
6822
6823 final int perm = checkComponentPermission(
6824 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006825 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006826 if (perm == PackageManager.PERMISSION_GRANTED) {
6827 return true;
6828 }
6829
Joe Onorato8a9b2202010-02-26 18:56:32 -08006830 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006831 return false;
6832 }
6833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006834 public void setDebugApp(String packageName, boolean waitForDebugger,
6835 boolean persistent) {
6836 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6837 "setDebugApp()");
6838
6839 // Note that this is not really thread safe if there are multiple
6840 // callers into it at the same time, but that's not a situation we
6841 // care about.
6842 if (persistent) {
6843 final ContentResolver resolver = mContext.getContentResolver();
6844 Settings.System.putString(
6845 resolver, Settings.System.DEBUG_APP,
6846 packageName);
6847 Settings.System.putInt(
6848 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6849 waitForDebugger ? 1 : 0);
6850 }
6851
6852 synchronized (this) {
6853 if (!persistent) {
6854 mOrigDebugApp = mDebugApp;
6855 mOrigWaitForDebugger = mWaitForDebugger;
6856 }
6857 mDebugApp = packageName;
6858 mWaitForDebugger = waitForDebugger;
6859 mDebugTransient = !persistent;
6860 if (packageName != null) {
6861 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006862 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 Binder.restoreCallingIdentity(origId);
6864 }
6865 }
6866 }
6867
Siva Velusamy92a8b222012-03-09 16:24:04 -08006868 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6869 synchronized (this) {
6870 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6871 if (!isDebuggable) {
6872 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6873 throw new SecurityException("Process not debuggable: " + app.packageName);
6874 }
6875 }
6876
6877 mOpenGlTraceApp = processName;
6878 }
6879 }
6880
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006881 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6882 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6883 synchronized (this) {
6884 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6885 if (!isDebuggable) {
6886 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6887 throw new SecurityException("Process not debuggable: " + app.packageName);
6888 }
6889 }
6890 mProfileApp = processName;
6891 mProfileFile = profileFile;
6892 if (mProfileFd != null) {
6893 try {
6894 mProfileFd.close();
6895 } catch (IOException e) {
6896 }
6897 mProfileFd = null;
6898 }
6899 mProfileFd = profileFd;
6900 mProfileType = 0;
6901 mAutoStopProfiler = autoStopProfiler;
6902 }
6903 }
6904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 public void setAlwaysFinish(boolean enabled) {
6906 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6907 "setAlwaysFinish()");
6908
6909 Settings.System.putInt(
6910 mContext.getContentResolver(),
6911 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6912
6913 synchronized (this) {
6914 mAlwaysFinishActivities = enabled;
6915 }
6916 }
6917
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006918 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006920 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006921 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006922 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 }
6924 }
6925
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006926 public boolean isUserAMonkey() {
6927 // For now the fact that there is a controller implies
6928 // we have a monkey.
6929 synchronized (this) {
6930 return mController != null;
6931 }
6932 }
6933
Jeff Sharkeya4620792011-05-20 15:29:23 -07006934 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006935 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6936 "registerProcessObserver()");
6937 synchronized (this) {
6938 mProcessObservers.register(observer);
6939 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006940 }
6941
6942 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006943 synchronized (this) {
6944 mProcessObservers.unregister(observer);
6945 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006946 }
6947
Daniel Sandler69a48172010-06-23 16:29:36 -04006948 public void setImmersive(IBinder token, boolean immersive) {
6949 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006950 ActivityRecord r = mMainStack.isInStackLocked(token);
6951 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006952 throw new IllegalArgumentException();
6953 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006954 r.immersive = immersive;
6955 }
6956 }
6957
6958 public boolean isImmersive(IBinder token) {
6959 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006960 ActivityRecord r = mMainStack.isInStackLocked(token);
6961 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006962 throw new IllegalArgumentException();
6963 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006964 return r.immersive;
6965 }
6966 }
6967
6968 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006969 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006970 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006971 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006972 return (r != null) ? r.immersive : false;
6973 }
6974 }
6975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006976 public final void enterSafeMode() {
6977 synchronized(this) {
6978 // It only makes sense to do this before the system is ready
6979 // and started launching other packages.
6980 if (!mSystemReady) {
6981 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006982 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006983 } catch (RemoteException e) {
6984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006985 }
6986 }
6987 }
6988
Jeff Brownb09abc12011-01-13 21:08:27 -08006989 public final void showSafeModeOverlay() {
6990 View v = LayoutInflater.from(mContext).inflate(
6991 com.android.internal.R.layout.safe_mode, null);
6992 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6993 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6994 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6995 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6996 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6997 lp.format = v.getBackground().getOpacity();
6998 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6999 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7000 ((WindowManager)mContext.getSystemService(
7001 Context.WINDOW_SERVICE)).addView(v, lp);
7002 }
7003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004 public void noteWakeupAlarm(IIntentSender sender) {
7005 if (!(sender instanceof PendingIntentRecord)) {
7006 return;
7007 }
7008 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7009 synchronized (stats) {
7010 if (mBatteryStatsService.isOnBattery()) {
7011 mBatteryStatsService.enforceCallingPermission();
7012 PendingIntentRecord rec = (PendingIntentRecord)sender;
7013 int MY_UID = Binder.getCallingUid();
7014 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7015 BatteryStatsImpl.Uid.Pkg pkg =
7016 stats.getPackageStatsLocked(uid, rec.key.packageName);
7017 pkg.incWakeupsLocked();
7018 }
7019 }
7020 }
7021
Dianne Hackborn64825172011-03-02 21:32:58 -08007022 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007024 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007026 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 // XXX Note: don't acquire main activity lock here, because the window
7028 // manager calls in with its locks held.
7029
7030 boolean killed = false;
7031 synchronized (mPidsSelfLocked) {
7032 int[] types = new int[pids.length];
7033 int worstType = 0;
7034 for (int i=0; i<pids.length; i++) {
7035 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7036 if (proc != null) {
7037 int type = proc.setAdj;
7038 types[i] = type;
7039 if (type > worstType) {
7040 worstType = type;
7041 }
7042 }
7043 }
7044
Dianne Hackborn64825172011-03-02 21:32:58 -08007045 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007047 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7048 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007049 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007051
7052 // If this is not a secure call, don't let it kill processes that
7053 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007054 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7055 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007056 }
7057
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007058 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 for (int i=0; i<pids.length; i++) {
7060 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7061 if (proc == null) {
7062 continue;
7063 }
7064 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007065 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007066 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007067 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7068 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007070 proc.killedBackground = true;
7071 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 }
7073 }
7074 }
7075 return killed;
7076 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007077
7078 @Override
7079 public boolean killProcessesBelowForeground(String reason) {
7080 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7081 throw new SecurityException("killProcessesBelowForeground() only available to system");
7082 }
7083
7084 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7085 }
7086
7087 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7088 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7089 throw new SecurityException("killProcessesBelowAdj() only available to system");
7090 }
7091
7092 boolean killed = false;
7093 synchronized (mPidsSelfLocked) {
7094 final int size = mPidsSelfLocked.size();
7095 for (int i = 0; i < size; i++) {
7096 final int pid = mPidsSelfLocked.keyAt(i);
7097 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7098 if (proc == null) continue;
7099
7100 final int adj = proc.setAdj;
7101 if (adj > belowAdj && !proc.killedBackground) {
7102 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7103 EventLog.writeEvent(
7104 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7105 killed = true;
7106 proc.killedBackground = true;
7107 Process.killProcessQuiet(pid);
7108 }
7109 }
7110 }
7111 return killed;
7112 }
7113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007114 public final void startRunning(String pkg, String cls, String action,
7115 String data) {
7116 synchronized(this) {
7117 if (mStartRunning) {
7118 return;
7119 }
7120 mStartRunning = true;
7121 mTopComponent = pkg != null && cls != null
7122 ? new ComponentName(pkg, cls) : null;
7123 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7124 mTopData = data;
7125 if (!mSystemReady) {
7126 return;
7127 }
7128 }
7129
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007130 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 }
7132
7133 private void retrieveSettings() {
7134 final ContentResolver resolver = mContext.getContentResolver();
7135 String debugApp = Settings.System.getString(
7136 resolver, Settings.System.DEBUG_APP);
7137 boolean waitForDebugger = Settings.System.getInt(
7138 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7139 boolean alwaysFinishActivities = Settings.System.getInt(
7140 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7141
7142 Configuration configuration = new Configuration();
7143 Settings.System.getConfiguration(resolver, configuration);
7144
7145 synchronized (this) {
7146 mDebugApp = mOrigDebugApp = debugApp;
7147 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7148 mAlwaysFinishActivities = alwaysFinishActivities;
7149 // This happens before any activities are started, so we can
7150 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007151 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007152 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 }
7154 }
7155
7156 public boolean testIsSystemReady() {
7157 // no need to synchronize(this) just to read & return the value
7158 return mSystemReady;
7159 }
7160
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007161 private static File getCalledPreBootReceiversFile() {
7162 File dataDir = Environment.getDataDirectory();
7163 File systemDir = new File(dataDir, "system");
7164 File fname = new File(systemDir, "called_pre_boots.dat");
7165 return fname;
7166 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007167
7168 static final int LAST_DONE_VERSION = 10000;
7169
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007170 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7171 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7172 File file = getCalledPreBootReceiversFile();
7173 FileInputStream fis = null;
7174 try {
7175 fis = new FileInputStream(file);
7176 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007177 int fvers = dis.readInt();
7178 if (fvers == LAST_DONE_VERSION) {
7179 String vers = dis.readUTF();
7180 String codename = dis.readUTF();
7181 String build = dis.readUTF();
7182 if (android.os.Build.VERSION.RELEASE.equals(vers)
7183 && android.os.Build.VERSION.CODENAME.equals(codename)
7184 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7185 int num = dis.readInt();
7186 while (num > 0) {
7187 num--;
7188 String pkg = dis.readUTF();
7189 String cls = dis.readUTF();
7190 lastDoneReceivers.add(new ComponentName(pkg, cls));
7191 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007192 }
7193 }
7194 } catch (FileNotFoundException e) {
7195 } catch (IOException e) {
7196 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7197 } finally {
7198 if (fis != null) {
7199 try {
7200 fis.close();
7201 } catch (IOException e) {
7202 }
7203 }
7204 }
7205 return lastDoneReceivers;
7206 }
7207
7208 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7209 File file = getCalledPreBootReceiversFile();
7210 FileOutputStream fos = null;
7211 DataOutputStream dos = null;
7212 try {
7213 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7214 fos = new FileOutputStream(file);
7215 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007216 dos.writeInt(LAST_DONE_VERSION);
7217 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007218 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007219 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007220 dos.writeInt(list.size());
7221 for (int i=0; i<list.size(); i++) {
7222 dos.writeUTF(list.get(i).getPackageName());
7223 dos.writeUTF(list.get(i).getClassName());
7224 }
7225 } catch (IOException e) {
7226 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7227 file.delete();
7228 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007229 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007230 if (dos != null) {
7231 try {
7232 dos.close();
7233 } catch (IOException e) {
7234 // TODO Auto-generated catch block
7235 e.printStackTrace();
7236 }
7237 }
7238 }
7239 }
7240
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007241 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 synchronized(this) {
7243 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007244 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 return;
7246 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007247
7248 // Check to see if there are any update receivers to run.
7249 if (!mDidUpdate) {
7250 if (mWaitingUpdate) {
7251 return;
7252 }
7253 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7254 List<ResolveInfo> ris = null;
7255 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007256 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007257 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007258 } catch (RemoteException e) {
7259 }
7260 if (ris != null) {
7261 for (int i=ris.size()-1; i>=0; i--) {
7262 if ((ris.get(i).activityInfo.applicationInfo.flags
7263 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7264 ris.remove(i);
7265 }
7266 }
7267 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007268
7269 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7270
7271 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007272 for (int i=0; i<ris.size(); i++) {
7273 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007274 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7275 if (lastDoneReceivers.contains(comp)) {
7276 ris.remove(i);
7277 i--;
7278 }
7279 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007280
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007281 for (int i=0; i<ris.size(); i++) {
7282 ActivityInfo ai = ris.get(i).activityInfo;
7283 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7284 doneReceivers.add(comp);
7285 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007286 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007287 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007288 finisher = new IIntentReceiver.Stub() {
7289 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007290 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007291 boolean sticky) {
7292 // The raw IIntentReceiver interface is called
7293 // with the AM lock held, so redispatch to
7294 // execute our code without the lock.
7295 mHandler.post(new Runnable() {
7296 public void run() {
7297 synchronized (ActivityManagerService.this) {
7298 mDidUpdate = true;
7299 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007300 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007301 showBootMessage(mContext.getText(
7302 R.string.android_upgrading_complete),
7303 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007304 systemReady(goingCallback);
7305 }
7306 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007307 }
7308 };
7309 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007310 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007311 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007312 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007313 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007314 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007315 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007316 mWaitingUpdate = true;
7317 }
7318 }
7319 }
7320 if (mWaitingUpdate) {
7321 return;
7322 }
7323 mDidUpdate = true;
7324 }
7325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 mSystemReady = true;
7327 if (!mStartRunning) {
7328 return;
7329 }
7330 }
7331
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007332 ArrayList<ProcessRecord> procsToKill = null;
7333 synchronized(mPidsSelfLocked) {
7334 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7335 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7336 if (!isAllowedWhileBooting(proc.info)){
7337 if (procsToKill == null) {
7338 procsToKill = new ArrayList<ProcessRecord>();
7339 }
7340 procsToKill.add(proc);
7341 }
7342 }
7343 }
7344
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007345 synchronized(this) {
7346 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007347 for (int i=procsToKill.size()-1; i>=0; i--) {
7348 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007349 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007350 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007351 }
7352 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007353
7354 // Now that we have cleaned up any update processes, we
7355 // are ready to start launching real processes and know that
7356 // we won't trample on them any more.
7357 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007358 }
7359
Joe Onorato8a9b2202010-02-26 18:56:32 -08007360 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007361 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 SystemClock.uptimeMillis());
7363
7364 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007365 // Make sure we have no pre-ready processes sitting around.
7366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7368 ResolveInfo ri = mContext.getPackageManager()
7369 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007370 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 CharSequence errorMsg = null;
7372 if (ri != null) {
7373 ActivityInfo ai = ri.activityInfo;
7374 ApplicationInfo app = ai.applicationInfo;
7375 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7376 mTopAction = Intent.ACTION_FACTORY_TEST;
7377 mTopData = null;
7378 mTopComponent = new ComponentName(app.packageName,
7379 ai.name);
7380 } else {
7381 errorMsg = mContext.getResources().getText(
7382 com.android.internal.R.string.factorytest_not_system);
7383 }
7384 } else {
7385 errorMsg = mContext.getResources().getText(
7386 com.android.internal.R.string.factorytest_no_action);
7387 }
7388 if (errorMsg != null) {
7389 mTopAction = null;
7390 mTopData = null;
7391 mTopComponent = null;
7392 Message msg = Message.obtain();
7393 msg.what = SHOW_FACTORY_ERROR_MSG;
7394 msg.getData().putCharSequence("msg", errorMsg);
7395 mHandler.sendMessage(msg);
7396 }
7397 }
7398 }
7399
7400 retrieveSettings();
7401
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007402 if (goingCallback != null) goingCallback.run();
7403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404 synchronized (this) {
7405 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7406 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007407 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007408 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 if (apps != null) {
7410 int N = apps.size();
7411 int i;
7412 for (i=0; i<N; i++) {
7413 ApplicationInfo info
7414 = (ApplicationInfo)apps.get(i);
7415 if (info != null &&
7416 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007417 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 }
7419 }
7420 }
7421 } catch (RemoteException ex) {
7422 // pm is in same process, this will never happen.
7423 }
7424 }
7425
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007426 // Start up initial activity.
7427 mBooting = true;
7428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007430 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007431 Message msg = Message.obtain();
7432 msg.what = SHOW_UID_ERROR_MSG;
7433 mHandler.sendMessage(msg);
7434 }
7435 } catch (RemoteException e) {
7436 }
7437
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007438 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 }
7440 }
7441
Dan Egnorb7f03672009-12-09 16:22:32 -08007442 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007443 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007445 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007446 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007447 startAppProblemLocked(app);
7448 app.stopFreezingAllLocked();
7449 return handleAppCrashLocked(app);
7450 }
7451
Dan Egnorb7f03672009-12-09 16:22:32 -08007452 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007453 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007455 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007456 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7457 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 startAppProblemLocked(app);
7459 app.stopFreezingAllLocked();
7460 }
7461
7462 /**
7463 * Generate a process error record, suitable for attachment to a ProcessRecord.
7464 *
7465 * @param app The ProcessRecord in which the error occurred.
7466 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7467 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007468 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 * @param shortMsg Short message describing the crash.
7470 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007471 * @param stackTrace Full crash stack trace, may be null.
7472 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 * @return Returns a fully-formed AppErrorStateInfo record.
7474 */
7475 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007476 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007479 report.condition = condition;
7480 report.processName = app.processName;
7481 report.pid = app.pid;
7482 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007483 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007484 report.shortMsg = shortMsg;
7485 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007486 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487
7488 return report;
7489 }
7490
Dan Egnor42471dd2010-01-07 17:25:22 -08007491 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 synchronized (this) {
7493 app.crashing = false;
7494 app.crashingReport = null;
7495 app.notResponding = false;
7496 app.notRespondingReport = null;
7497 if (app.anrDialog == fromDialog) {
7498 app.anrDialog = null;
7499 }
7500 if (app.waitDialog == fromDialog) {
7501 app.waitDialog = null;
7502 }
7503 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007504 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007505 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007506 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7507 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007508 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 }
7511 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007512
Dan Egnorb7f03672009-12-09 16:22:32 -08007513 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007514 if (mHeadless) {
7515 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7516 return false;
7517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007518 long now = SystemClock.uptimeMillis();
7519
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007520 Long crashTime;
7521 if (!app.isolated) {
7522 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7523 } else {
7524 crashTime = null;
7525 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007526 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007528 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007530 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007531 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007532 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7533 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007535 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007537 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 }
7539 }
7540 if (!app.persistent) {
7541 // We don't want to start this process again until the user
7542 // explicitly does so... but for persistent process, we really
7543 // need to keep it running. If a persistent process is actually
7544 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007545 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007547 if (!app.isolated) {
7548 // XXX We don't have a way to mark isolated processes
7549 // as bad, since they don't have a peristent identity.
7550 mBadProcesses.put(app.info.processName, app.uid, now);
7551 mProcessCrashTimes.remove(app.info.processName, app.uid);
7552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007555 // Don't let services in this process be restarted and potentially
7556 // annoy the user repeatedly. Unless it is persistent, since those
7557 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007558 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007559 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 return false;
7561 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007562 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007563 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007564 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007565 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007566 // If the top running activity is from this crashing
7567 // process, then terminate it to avoid getting in a loop.
7568 Slog.w(TAG, " Force finishing activity "
7569 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007570 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007571 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007572 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007573 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007574 // stopped, to avoid a situation where one will get
7575 // re-start our crashing activity once it gets resumed again.
7576 index--;
7577 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007578 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007579 if (r.state == ActivityState.RESUMED
7580 || r.state == ActivityState.PAUSING
7581 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007582 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007583 Slog.w(TAG, " Force finishing activity "
7584 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007585 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007586 Activity.RESULT_CANCELED, null, "crashed");
7587 }
7588 }
7589 }
7590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 }
7592
7593 // Bump up the crash count of any services currently running in the proc.
7594 if (app.services.size() != 0) {
7595 // Any services running in the application need to be placed
7596 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007597 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007599 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 sr.crashCount++;
7601 }
7602 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007603
7604 // If the crashing process is what we consider to be the "home process" and it has been
7605 // replaced by a third-party app, clear the package preferred activities from packages
7606 // with a home activity running in the process to prevent a repeatedly crashing app
7607 // from blocking the user to manually clear the list.
7608 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7609 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7610 Iterator it = mHomeProcess.activities.iterator();
7611 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007612 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007613 if (r.isHomeActivity) {
7614 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7615 try {
7616 ActivityThread.getPackageManager()
7617 .clearPackagePreferredActivities(r.packageName);
7618 } catch (RemoteException c) {
7619 // pm is in same process, this will never happen.
7620 }
7621 }
7622 }
7623 }
7624
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007625 if (!app.isolated) {
7626 // XXX Can't keep track of crash times for isolated processes,
7627 // because they don't have a perisistent identity.
7628 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7629 }
7630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 return true;
7632 }
7633
7634 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007635 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7636 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 skipCurrentReceiverLocked(app);
7638 }
7639
7640 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007641 for (BroadcastQueue queue : mBroadcastQueues) {
7642 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 }
7644 }
7645
Dan Egnor60d87622009-12-16 16:32:58 -08007646 /**
7647 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7648 * The application process will exit immediately after this call returns.
7649 * @param app object of the crashing app, null for the system server
7650 * @param crashInfo describing the exception
7651 */
7652 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007653 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007654 final String processName = app == null ? "system_server"
7655 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007656
7657 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007658 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007659 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007660 crashInfo.exceptionClassName,
7661 crashInfo.exceptionMessage,
7662 crashInfo.throwFileName,
7663 crashInfo.throwLineNumber);
7664
Jeff Sharkeya353d262011-10-28 11:12:06 -07007665 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007666
7667 crashApplication(r, crashInfo);
7668 }
7669
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007670 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007671 IBinder app,
7672 int violationMask,
7673 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007674 ProcessRecord r = findAppProcess(app, "StrictMode");
7675 if (r == null) {
7676 return;
7677 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007678
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007679 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007680 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007681 boolean logIt = true;
7682 synchronized (mAlreadyLoggedViolatedStacks) {
7683 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7684 logIt = false;
7685 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007686 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007687 // the relative pain numbers, without logging all
7688 // the stack traces repeatedly. We'd want to do
7689 // likewise in the client code, which also does
7690 // dup suppression, before the Binder call.
7691 } else {
7692 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7693 mAlreadyLoggedViolatedStacks.clear();
7694 }
7695 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7696 }
7697 }
7698 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007699 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007700 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007701 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007702
7703 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7704 AppErrorResult result = new AppErrorResult();
7705 synchronized (this) {
7706 final long origId = Binder.clearCallingIdentity();
7707
7708 Message msg = Message.obtain();
7709 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7710 HashMap<String, Object> data = new HashMap<String, Object>();
7711 data.put("result", result);
7712 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007713 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007714 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007715 msg.obj = data;
7716 mHandler.sendMessage(msg);
7717
7718 Binder.restoreCallingIdentity(origId);
7719 }
7720 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007721 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007722 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007723 }
7724
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007725 // Depending on the policy in effect, there could be a bunch of
7726 // these in quick succession so we try to batch these together to
7727 // minimize disk writes, number of dropbox entries, and maximize
7728 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007729 private void logStrictModeViolationToDropBox(
7730 ProcessRecord process,
7731 StrictMode.ViolationInfo info) {
7732 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007733 return;
7734 }
7735 final boolean isSystemApp = process == null ||
7736 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7737 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007738 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007739 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7740 final DropBoxManager dbox = (DropBoxManager)
7741 mContext.getSystemService(Context.DROPBOX_SERVICE);
7742
7743 // Exit early if the dropbox isn't configured to accept this report type.
7744 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7745
7746 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007747 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007748 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7749 synchronized (sb) {
7750 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007751 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007752 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7753 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007754 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7755 if (info.violationNumThisLoop != 0) {
7756 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7757 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007758 if (info.numAnimationsRunning != 0) {
7759 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7760 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007761 if (info.broadcastIntentAction != null) {
7762 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7763 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007764 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007765 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007766 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007767 if (info.numInstances != -1) {
7768 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7769 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007770 if (info.tags != null) {
7771 for (String tag : info.tags) {
7772 sb.append("Span-Tag: ").append(tag).append("\n");
7773 }
7774 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007775 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007776 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7777 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007778 }
7779 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007780
7781 // Only buffer up to ~64k. Various logging bits truncate
7782 // things at 128k.
7783 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007784 }
7785
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007786 // Flush immediately if the buffer's grown too large, or this
7787 // is a non-system app. Non-system apps are isolated with a
7788 // different tag & policy and not batched.
7789 //
7790 // Batching is useful during internal testing with
7791 // StrictMode settings turned up high. Without batching,
7792 // thousands of separate files could be created on boot.
7793 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007794 new Thread("Error dump: " + dropboxTag) {
7795 @Override
7796 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007797 String report;
7798 synchronized (sb) {
7799 report = sb.toString();
7800 sb.delete(0, sb.length());
7801 sb.trimToSize();
7802 }
7803 if (report.length() != 0) {
7804 dbox.addText(dropboxTag, report);
7805 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007806 }
7807 }.start();
7808 return;
7809 }
7810
7811 // System app batching:
7812 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007813 // An existing dropbox-writing thread is outstanding, so
7814 // we don't need to start it up. The existing thread will
7815 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007816 return;
7817 }
7818
7819 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7820 // (After this point, we shouldn't access AMS internal data structures.)
7821 new Thread("Error dump: " + dropboxTag) {
7822 @Override
7823 public void run() {
7824 // 5 second sleep to let stacks arrive and be batched together
7825 try {
7826 Thread.sleep(5000); // 5 seconds
7827 } catch (InterruptedException e) {}
7828
7829 String errorReport;
7830 synchronized (mStrictModeBuffer) {
7831 errorReport = mStrictModeBuffer.toString();
7832 if (errorReport.length() == 0) {
7833 return;
7834 }
7835 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7836 mStrictModeBuffer.trimToSize();
7837 }
7838 dbox.addText(dropboxTag, errorReport);
7839 }
7840 }.start();
7841 }
7842
Dan Egnor60d87622009-12-16 16:32:58 -08007843 /**
7844 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7845 * @param app object of the crashing app, null for the system server
7846 * @param tag reported by the caller
7847 * @param crashInfo describing the context of the error
7848 * @return true if the process should exit immediately (WTF is fatal)
7849 */
7850 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007851 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007852 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007853 final String processName = app == null ? "system_server"
7854 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007855
7856 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007857 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007858 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007859 tag, crashInfo.exceptionMessage);
7860
Jeff Sharkeya353d262011-10-28 11:12:06 -07007861 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007862
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007863 if (r != null && r.pid != Process.myPid() &&
7864 Settings.Secure.getInt(mContext.getContentResolver(),
7865 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007866 crashApplication(r, crashInfo);
7867 return true;
7868 } else {
7869 return false;
7870 }
7871 }
7872
7873 /**
7874 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7875 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7876 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007877 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007878 if (app == null) {
7879 return null;
7880 }
7881
7882 synchronized (this) {
7883 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7884 final int NA = apps.size();
7885 for (int ia=0; ia<NA; ia++) {
7886 ProcessRecord p = apps.valueAt(ia);
7887 if (p.thread != null && p.thread.asBinder() == app) {
7888 return p;
7889 }
7890 }
7891 }
7892
Dianne Hackborncb44d962011-03-10 17:02:27 -08007893 Slog.w(TAG, "Can't find mystery application for " + reason
7894 + " from pid=" + Binder.getCallingPid()
7895 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007896 return null;
7897 }
7898 }
7899
7900 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007901 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7902 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007903 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007904 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7905 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007906 // Watchdog thread ends up invoking this function (with
7907 // a null ProcessRecord) to add the stack file to dropbox.
7908 // Do not acquire a lock on this (am) in such cases, as it
7909 // could cause a potential deadlock, if and when watchdog
7910 // is invoked due to unavailability of lock on am and it
7911 // would prevent watchdog from killing system_server.
7912 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007913 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007914 return;
7915 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007916 // Note: ProcessRecord 'process' is guarded by the service
7917 // instance. (notably process.pkgList, which could otherwise change
7918 // concurrently during execution of this method)
7919 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007920 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007921 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007922 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007923 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7924 for (String pkg : process.pkgList) {
7925 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007926 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007927 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007928 if (pi != null) {
7929 sb.append(" v").append(pi.versionCode);
7930 if (pi.versionName != null) {
7931 sb.append(" (").append(pi.versionName).append(")");
7932 }
7933 }
7934 } catch (RemoteException e) {
7935 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007936 }
Dan Egnora455d192010-03-12 08:52:28 -08007937 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007938 }
Dan Egnora455d192010-03-12 08:52:28 -08007939 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007940 }
7941
7942 private static String processClass(ProcessRecord process) {
7943 if (process == null || process.pid == MY_PID) {
7944 return "system_server";
7945 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7946 return "system_app";
7947 } else {
7948 return "data_app";
7949 }
7950 }
7951
7952 /**
7953 * Write a description of an error (crash, WTF, ANR) to the drop box.
7954 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7955 * @param process which caused the error, null means the system server
7956 * @param activity which triggered the error, null if unknown
7957 * @param parent activity related to the error, null if unknown
7958 * @param subject line related to the error, null if absent
7959 * @param report in long form describing the error, null if absent
7960 * @param logFile to include in the report, null if none
7961 * @param crashInfo giving an application stack trace, null if absent
7962 */
7963 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007964 ProcessRecord process, String processName, ActivityRecord activity,
7965 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007966 final String report, final File logFile,
7967 final ApplicationErrorReport.CrashInfo crashInfo) {
7968 // NOTE -- this must never acquire the ActivityManagerService lock,
7969 // otherwise the watchdog may be prevented from resetting the system.
7970
7971 final String dropboxTag = processClass(process) + "_" + eventType;
7972 final DropBoxManager dbox = (DropBoxManager)
7973 mContext.getSystemService(Context.DROPBOX_SERVICE);
7974
7975 // Exit early if the dropbox isn't configured to accept this report type.
7976 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7977
7978 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007979 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007980 if (activity != null) {
7981 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7982 }
7983 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7984 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7985 }
7986 if (parent != null && parent != activity) {
7987 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7988 }
7989 if (subject != null) {
7990 sb.append("Subject: ").append(subject).append("\n");
7991 }
7992 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007993 if (Debug.isDebuggerConnected()) {
7994 sb.append("Debugger: Connected\n");
7995 }
Dan Egnora455d192010-03-12 08:52:28 -08007996 sb.append("\n");
7997
7998 // Do the rest in a worker thread to avoid blocking the caller on I/O
7999 // (After this point, we shouldn't access AMS internal data structures.)
8000 Thread worker = new Thread("Error dump: " + dropboxTag) {
8001 @Override
8002 public void run() {
8003 if (report != null) {
8004 sb.append(report);
8005 }
8006 if (logFile != null) {
8007 try {
8008 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8009 } catch (IOException e) {
8010 Slog.e(TAG, "Error reading " + logFile, e);
8011 }
8012 }
8013 if (crashInfo != null && crashInfo.stackTrace != null) {
8014 sb.append(crashInfo.stackTrace);
8015 }
8016
8017 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8018 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8019 if (lines > 0) {
8020 sb.append("\n");
8021
8022 // Merge several logcat streams, and take the last N lines
8023 InputStreamReader input = null;
8024 try {
8025 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8026 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8027 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8028
8029 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8030 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8031 input = new InputStreamReader(logcat.getInputStream());
8032
8033 int num;
8034 char[] buf = new char[8192];
8035 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8036 } catch (IOException e) {
8037 Slog.e(TAG, "Error running logcat", e);
8038 } finally {
8039 if (input != null) try { input.close(); } catch (IOException e) {}
8040 }
8041 }
8042
8043 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008044 }
Dan Egnora455d192010-03-12 08:52:28 -08008045 };
8046
8047 if (process == null || process.pid == MY_PID) {
8048 worker.run(); // We may be about to die -- need to run this synchronously
8049 } else {
8050 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008051 }
8052 }
8053
8054 /**
8055 * Bring up the "unexpected error" dialog box for a crashing app.
8056 * Deal with edge cases (intercepts from instrumented applications,
8057 * ActivityController, error intent receivers, that sort of thing).
8058 * @param r the application crashing
8059 * @param crashInfo describing the failure
8060 */
8061 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008062 long timeMillis = System.currentTimeMillis();
8063 String shortMsg = crashInfo.exceptionClassName;
8064 String longMsg = crashInfo.exceptionMessage;
8065 String stackTrace = crashInfo.stackTrace;
8066 if (shortMsg != null && longMsg != null) {
8067 longMsg = shortMsg + ": " + longMsg;
8068 } else if (shortMsg != null) {
8069 longMsg = shortMsg;
8070 }
8071
Dan Egnor60d87622009-12-16 16:32:58 -08008072 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008074 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 try {
8076 String name = r != null ? r.processName : null;
8077 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008078 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008079 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008080 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 + " at watcher's request");
8082 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008083 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 }
8085 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008086 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 }
8088 }
8089
8090 final long origId = Binder.clearCallingIdentity();
8091
8092 // If this process is running instrumentation, finish it.
8093 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008094 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008096 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8097 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 Bundle info = new Bundle();
8099 info.putString("shortMsg", shortMsg);
8100 info.putString("longMsg", longMsg);
8101 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8102 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008103 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 }
8105
Dan Egnor60d87622009-12-16 16:32:58 -08008106 // If we can't identify the process or it's already exceeded its crash quota,
8107 // quit right away without showing a crash dialog.
8108 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008110 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008111 }
8112
8113 Message msg = Message.obtain();
8114 msg.what = SHOW_ERROR_MSG;
8115 HashMap data = new HashMap();
8116 data.put("result", result);
8117 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 msg.obj = data;
8119 mHandler.sendMessage(msg);
8120
8121 Binder.restoreCallingIdentity(origId);
8122 }
8123
8124 int res = result.get();
8125
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008126 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008127 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008128 if (r != null && !r.isolated) {
8129 // XXX Can't keep track of crash time for isolated processes,
8130 // since they don't have a persistent identity.
8131 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 SystemClock.uptimeMillis());
8133 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008134 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008135 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008136 }
8137 }
8138
8139 if (appErrorIntent != null) {
8140 try {
8141 mContext.startActivity(appErrorIntent);
8142 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008143 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008147
8148 Intent createAppErrorIntentLocked(ProcessRecord r,
8149 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8150 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008151 if (report == null) {
8152 return null;
8153 }
8154 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8155 result.setComponent(r.errorReportReceiver);
8156 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8157 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8158 return result;
8159 }
8160
Dan Egnorb7f03672009-12-09 16:22:32 -08008161 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8162 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008163 if (r.errorReportReceiver == null) {
8164 return null;
8165 }
8166
8167 if (!r.crashing && !r.notResponding) {
8168 return null;
8169 }
8170
Dan Egnorb7f03672009-12-09 16:22:32 -08008171 ApplicationErrorReport report = new ApplicationErrorReport();
8172 report.packageName = r.info.packageName;
8173 report.installerPackageName = r.errorReportReceiver.getPackageName();
8174 report.processName = r.processName;
8175 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008176 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008177
Dan Egnorb7f03672009-12-09 16:22:32 -08008178 if (r.crashing) {
8179 report.type = ApplicationErrorReport.TYPE_CRASH;
8180 report.crashInfo = crashInfo;
8181 } else if (r.notResponding) {
8182 report.type = ApplicationErrorReport.TYPE_ANR;
8183 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008184
Dan Egnorb7f03672009-12-09 16:22:32 -08008185 report.anrInfo.activity = r.notRespondingReport.tag;
8186 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8187 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008188 }
8189
Dan Egnorb7f03672009-12-09 16:22:32 -08008190 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008191 }
8192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008194 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195 // assume our apps are happy - lazy create the list
8196 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8197
8198 synchronized (this) {
8199
8200 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008201 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8202 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8204 // This one's in trouble, so we'll generate a report for it
8205 // crashes are higher priority (in case there's a crash *and* an anr)
8206 ActivityManager.ProcessErrorStateInfo report = null;
8207 if (app.crashing) {
8208 report = app.crashingReport;
8209 } else if (app.notResponding) {
8210 report = app.notRespondingReport;
8211 }
8212
8213 if (report != null) {
8214 if (errList == null) {
8215 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8216 }
8217 errList.add(report);
8218 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008219 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 " crashing = " + app.crashing +
8221 " notResponding = " + app.notResponding);
8222 }
8223 }
8224 }
8225 }
8226
8227 return errList;
8228 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008229
8230 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008231 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008232 if (currApp != null) {
8233 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8234 }
8235 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008236 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8237 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008238 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8239 if (currApp != null) {
8240 currApp.lru = 0;
8241 }
8242 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008243 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008244 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8245 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8246 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8247 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8248 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8249 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8250 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8251 } else {
8252 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8253 }
8254 }
8255
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008256 private void fillInProcMemInfo(ProcessRecord app,
8257 ActivityManager.RunningAppProcessInfo outInfo) {
8258 outInfo.pid = app.pid;
8259 outInfo.uid = app.info.uid;
8260 if (mHeavyWeightProcess == app) {
8261 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8262 }
8263 if (app.persistent) {
8264 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8265 }
8266 outInfo.lastTrimLevel = app.trimMemoryLevel;
8267 int adj = app.curAdj;
8268 outInfo.importance = oomAdjToImportance(adj, outInfo);
8269 outInfo.importanceReasonCode = app.adjTypeCode;
8270 }
8271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008273 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 // Lazy instantiation of list
8275 List<ActivityManager.RunningAppProcessInfo> runList = null;
8276 synchronized (this) {
8277 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008278 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8279 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8281 // Generate process state info for running application
8282 ActivityManager.RunningAppProcessInfo currApp =
8283 new ActivityManager.RunningAppProcessInfo(app.processName,
8284 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008285 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008286 if (app.adjSource instanceof ProcessRecord) {
8287 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008288 currApp.importanceReasonImportance = oomAdjToImportance(
8289 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008290 } else if (app.adjSource instanceof ActivityRecord) {
8291 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008292 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8293 }
8294 if (app.adjTarget instanceof ComponentName) {
8295 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8296 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008297 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 // + " lru=" + currApp.lru);
8299 if (runList == null) {
8300 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8301 }
8302 runList.add(currApp);
8303 }
8304 }
8305 }
8306 return runList;
8307 }
8308
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008309 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008310 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008311 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8312 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8313 if (runningApps != null && runningApps.size() > 0) {
8314 Set<String> extList = new HashSet<String>();
8315 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8316 if (app.pkgList != null) {
8317 for (String pkg : app.pkgList) {
8318 extList.add(pkg);
8319 }
8320 }
8321 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008322 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008323 for (String pkg : extList) {
8324 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008325 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008326 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8327 retList.add(info);
8328 }
8329 } catch (RemoteException e) {
8330 }
8331 }
8332 }
8333 return retList;
8334 }
8335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008337 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8338 enforceNotIsolatedCaller("getMyMemoryState");
8339 synchronized (this) {
8340 ProcessRecord proc;
8341 synchronized (mPidsSelfLocked) {
8342 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8343 }
8344 fillInProcMemInfo(proc, outInfo);
8345 }
8346 }
8347
8348 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008349 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008350 if (checkCallingPermission(android.Manifest.permission.DUMP)
8351 != PackageManager.PERMISSION_GRANTED) {
8352 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8353 + Binder.getCallingPid()
8354 + ", uid=" + Binder.getCallingUid()
8355 + " without permission "
8356 + android.Manifest.permission.DUMP);
8357 return;
8358 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008359
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008360 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008361 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008362 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008363
8364 int opti = 0;
8365 while (opti < args.length) {
8366 String opt = args[opti];
8367 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8368 break;
8369 }
8370 opti++;
8371 if ("-a".equals(opt)) {
8372 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008373 } else if ("-c".equals(opt)) {
8374 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008375 } else if ("-h".equals(opt)) {
8376 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008377 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008378 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008379 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008380 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8381 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8382 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008383 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008384 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008385 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008386 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008387 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008388 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008389 pw.println(" all: dump all activities");
8390 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008391 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008392 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8393 pw.println(" a partial substring in a component name, a");
8394 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008395 pw.println(" -a: include all available server state.");
8396 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008397 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008398 } else {
8399 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008401 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008402
8403 long origId = Binder.clearCallingIdentity();
8404 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008405 // Is the caller requesting to dump a particular piece of data?
8406 if (opti < args.length) {
8407 String cmd = args[opti];
8408 opti++;
8409 if ("activities".equals(cmd) || "a".equals(cmd)) {
8410 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008411 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008413 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008414 String[] newArgs;
8415 String name;
8416 if (opti >= args.length) {
8417 name = null;
8418 newArgs = EMPTY_STRING_ARRAY;
8419 } else {
8420 name = args[opti];
8421 opti++;
8422 newArgs = new String[args.length - opti];
8423 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8424 args.length - opti);
8425 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008426 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008427 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008428 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008429 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008430 String[] newArgs;
8431 String name;
8432 if (opti >= args.length) {
8433 name = null;
8434 newArgs = EMPTY_STRING_ARRAY;
8435 } else {
8436 name = args[opti];
8437 opti++;
8438 newArgs = new String[args.length - opti];
8439 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8440 args.length - opti);
8441 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008442 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008443 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008444 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008445 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008446 String[] newArgs;
8447 String name;
8448 if (opti >= args.length) {
8449 name = null;
8450 newArgs = EMPTY_STRING_ARRAY;
8451 } else {
8452 name = args[opti];
8453 opti++;
8454 newArgs = new String[args.length - opti];
8455 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8456 args.length - opti);
8457 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008458 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008459 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008460 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008461 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8462 synchronized (this) {
8463 dumpOomLocked(fd, pw, args, opti, true);
8464 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008465 } else if ("provider".equals(cmd)) {
8466 String[] newArgs;
8467 String name;
8468 if (opti >= args.length) {
8469 name = null;
8470 newArgs = EMPTY_STRING_ARRAY;
8471 } else {
8472 name = args[opti];
8473 opti++;
8474 newArgs = new String[args.length - opti];
8475 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8476 }
8477 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8478 pw.println("No providers match: " + name);
8479 pw.println("Use -h for help.");
8480 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008481 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8482 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008483 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008484 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008485 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008486 String[] newArgs;
8487 String name;
8488 if (opti >= args.length) {
8489 name = null;
8490 newArgs = EMPTY_STRING_ARRAY;
8491 } else {
8492 name = args[opti];
8493 opti++;
8494 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008495 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8496 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008497 }
8498 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8499 pw.println("No services match: " + name);
8500 pw.println("Use -h for help.");
8501 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008502 } else if ("package".equals(cmd)) {
8503 String[] newArgs;
8504 if (opti >= args.length) {
8505 pw.println("package: no package name specified");
8506 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008507 } else {
8508 dumpPackage = args[opti];
8509 opti++;
8510 newArgs = new String[args.length - opti];
8511 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8512 args.length - opti);
8513 args = newArgs;
8514 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008515 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008516 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008517 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8518 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008519 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008520 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008521 } else {
8522 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008523 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8524 pw.println("Bad activity command, or no activities match: " + cmd);
8525 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008526 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008527 }
8528 if (!more) {
8529 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008530 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008533
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 // No piece of data specified, dump everything.
8535 synchronized (this) {
8536 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008537 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 if (needSep) {
8539 pw.println(" ");
8540 }
8541 if (dumpAll) {
8542 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008543 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008544 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008545 if (needSep) {
8546 pw.println(" ");
8547 }
8548 if (dumpAll) {
8549 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008550 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008551 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008552 if (needSep) {
8553 pw.println(" ");
8554 }
8555 if (dumpAll) {
8556 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008557 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008558 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008559 if (needSep) {
8560 pw.println(" ");
8561 }
8562 if (dumpAll) {
8563 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008564 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008565 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008566 if (needSep) {
8567 pw.println(" ");
8568 }
8569 if (dumpAll) {
8570 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008571 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008572 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008574 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008575 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008576
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008577 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008578 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008579 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8580 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008581 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8582 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008583 pw.println(" ");
8584 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008585 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8586 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008587 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008589 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008590 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008591 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008592 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008593 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008594 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008595 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008596 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008597 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008598 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008599 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8600 pw.println(" ");
8601 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008602 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008603 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008604 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008605 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008606 pw.println(" ");
8607 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008608 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008609 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008612 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008613 if (mMainStack.mPausingActivity != null) {
8614 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008615 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008616 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008617 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008618 if (dumpAll) {
8619 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8620 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008621 pw.println(" mDismissKeyguardOnNextActivity: "
8622 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008625 if (mRecentTasks.size() > 0) {
8626 pw.println();
8627 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008628
8629 final int N = mRecentTasks.size();
8630 for (int i=0; i<N; i++) {
8631 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008632 if (dumpPackage != null) {
8633 if (tr.realActivity == null ||
8634 !dumpPackage.equals(tr.realActivity)) {
8635 continue;
8636 }
8637 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008638 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8639 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008640 if (dumpAll) {
8641 mRecentTasks.get(i).dump(pw, " ");
8642 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 }
8644 }
8645
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008646 if (dumpAll) {
8647 pw.println(" ");
8648 pw.println(" mCurTask: " + mCurTask);
8649 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008650
8651 return true;
8652 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008653
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008654 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008655 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008656 boolean needSep = false;
8657 int numPers = 0;
8658
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008659 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8660
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008661 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8663 final int NA = procs.size();
8664 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008665 ProcessRecord r = procs.valueAt(ia);
8666 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8667 continue;
8668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 if (!needSep) {
8670 pw.println(" All known processes:");
8671 needSep = true;
8672 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008673 pw.print(r.persistent ? " *PERS*" : " *APP*");
8674 pw.print(" UID "); pw.print(procs.keyAt(ia));
8675 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 r.dump(pw, " ");
8677 if (r.persistent) {
8678 numPers++;
8679 }
8680 }
8681 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008682 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008683
8684 if (mIsolatedProcesses.size() > 0) {
8685 if (needSep) pw.println(" ");
8686 needSep = true;
8687 pw.println(" Isolated process list (sorted by uid):");
8688 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8689 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8690 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8691 continue;
8692 }
8693 pw.println(String.format("%sIsolated #%2d: %s",
8694 " ", i, r.toString()));
8695 }
8696 }
8697
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008698 if (mLruProcesses.size() > 0) {
8699 if (needSep) pw.println(" ");
8700 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008701 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008702 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008703 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008704 needSep = true;
8705 }
8706
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008707 if (dumpAll) {
8708 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008709 boolean printed = false;
8710 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8711 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8712 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8713 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008714 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008715 if (!printed) {
8716 if (needSep) pw.println(" ");
8717 needSep = true;
8718 pw.println(" PID mappings:");
8719 printed = true;
8720 }
8721 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8722 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 }
8724 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008725 }
8726
8727 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008728 synchronized (mPidsSelfLocked) {
8729 boolean printed = false;
8730 for (int i=0; i<mForegroundProcesses.size(); i++) {
8731 ProcessRecord r = mPidsSelfLocked.get(
8732 mForegroundProcesses.valueAt(i).pid);
8733 if (dumpPackage != null && (r == null
8734 || !dumpPackage.equals(r.info.packageName))) {
8735 continue;
8736 }
8737 if (!printed) {
8738 if (needSep) pw.println(" ");
8739 needSep = true;
8740 pw.println(" Foreground Processes:");
8741 printed = true;
8742 }
8743 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8744 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 }
8748
8749 if (mPersistentStartingProcesses.size() > 0) {
8750 if (needSep) pw.println(" ");
8751 needSep = true;
8752 pw.println(" Persisent processes that are starting:");
8753 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008754 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008757 if (mRemovedProcesses.size() > 0) {
8758 if (needSep) pw.println(" ");
8759 needSep = true;
8760 pw.println(" Processes that are being removed:");
8761 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008762 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008763 }
8764
8765 if (mProcessesOnHold.size() > 0) {
8766 if (needSep) pw.println(" ");
8767 needSep = true;
8768 pw.println(" Processes that are on old until the system is ready:");
8769 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008770 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008773 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008774
8775 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 long now = SystemClock.uptimeMillis();
8778 for (Map.Entry<String, SparseArray<Long>> procs
8779 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008780 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008781 SparseArray<Long> uids = procs.getValue();
8782 final int N = uids.size();
8783 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008784 int puid = uids.keyAt(i);
8785 ProcessRecord r = mProcessNames.get(pname, puid);
8786 if (dumpPackage != null && (r == null
8787 || !dumpPackage.equals(r.info.packageName))) {
8788 continue;
8789 }
8790 if (!printed) {
8791 if (needSep) pw.println(" ");
8792 needSep = true;
8793 pw.println(" Time since processes crashed:");
8794 printed = true;
8795 }
8796 pw.print(" Process "); pw.print(pname);
8797 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008798 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008799 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8800 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008801 }
8802 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008805 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008806 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008807 for (Map.Entry<String, SparseArray<Long>> procs
8808 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008809 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810 SparseArray<Long> uids = procs.getValue();
8811 final int N = uids.size();
8812 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008813 int puid = uids.keyAt(i);
8814 ProcessRecord r = mProcessNames.get(pname, puid);
8815 if (dumpPackage != null && (r == null
8816 || !dumpPackage.equals(r.info.packageName))) {
8817 continue;
8818 }
8819 if (!printed) {
8820 if (needSep) pw.println(" ");
8821 needSep = true;
8822 pw.println(" Bad processes:");
8823 }
8824 pw.print(" Bad process "); pw.print(pname);
8825 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008826 pw.print(": crashed at time ");
8827 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 }
8829 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008832 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008833 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008834 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008835 if (dumpAll) {
8836 StringBuilder sb = new StringBuilder(128);
8837 sb.append(" mPreviousProcessVisibleTime: ");
8838 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8839 pw.println(sb);
8840 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008841 if (mHeavyWeightProcess != null) {
8842 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8843 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008844 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008845 if (dumpAll) {
8846 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008847 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008848 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008849 for (Map.Entry<String, Integer> entry
8850 : mCompatModePackages.getPackages().entrySet()) {
8851 String pkg = entry.getKey();
8852 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008853 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8854 continue;
8855 }
8856 if (!printed) {
8857 pw.println(" mScreenCompatPackages:");
8858 printed = true;
8859 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008860 pw.print(" "); pw.print(pkg); pw.print(": ");
8861 pw.print(mode); pw.println();
8862 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008863 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008864 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008865 if (mSleeping || mWentToSleep || mLockScreenShown) {
8866 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8867 + " mLockScreenShown " + mLockScreenShown);
8868 }
8869 if (mShuttingDown) {
8870 pw.println(" mShuttingDown=" + mShuttingDown);
8871 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008872 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8873 || mOrigWaitForDebugger) {
8874 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8875 + " mDebugTransient=" + mDebugTransient
8876 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8877 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008878 if (mOpenGlTraceApp != null) {
8879 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8880 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008881 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8882 || mProfileFd != null) {
8883 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8884 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8885 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8886 + mAutoStopProfiler);
8887 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008888 if (mAlwaysFinishActivities || mController != null) {
8889 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8890 + " mController=" + mController);
8891 }
8892 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008893 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008895 + " mProcessesReady=" + mProcessesReady
8896 + " mSystemReady=" + mSystemReady);
8897 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 + " mBooted=" + mBooted
8899 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008900 pw.print(" mLastPowerCheckRealtime=");
8901 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8902 pw.println("");
8903 pw.print(" mLastPowerCheckUptime=");
8904 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8905 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008906 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8907 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008908 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008909 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8910 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008911 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008912
8913 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 }
8915
Dianne Hackborn287952c2010-09-22 22:34:31 -07008916 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008917 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008918 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008919 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008920 long now = SystemClock.uptimeMillis();
8921 for (int i=0; i<mProcessesToGc.size(); i++) {
8922 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008923 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8924 continue;
8925 }
8926 if (!printed) {
8927 if (needSep) pw.println(" ");
8928 needSep = true;
8929 pw.println(" Processes that are waiting to GC:");
8930 printed = true;
8931 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008932 pw.print(" Process "); pw.println(proc);
8933 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8934 pw.print(", last gced=");
8935 pw.print(now-proc.lastRequestedGc);
8936 pw.print(" ms ago, last lowMem=");
8937 pw.print(now-proc.lastLowMemory);
8938 pw.println(" ms ago");
8939
8940 }
8941 }
8942 return needSep;
8943 }
8944
8945 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8946 int opti, boolean dumpAll) {
8947 boolean needSep = false;
8948
8949 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008950 if (needSep) pw.println(" ");
8951 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008952 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008953 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008954 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008955 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8956 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8957 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8958 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8959 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008960 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008961 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008962 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008963 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008964 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008965 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008966
8967 if (needSep) pw.println(" ");
8968 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008969 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008970 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008971 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008972 needSep = true;
8973 }
8974
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008976
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008977 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008978 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008979 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008980 if (mHeavyWeightProcess != null) {
8981 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8982 }
8983
8984 return true;
8985 }
8986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008987 /**
8988 * There are three ways to call this:
8989 * - no service specified: dump all the services
8990 * - a flattened component name that matched an existing service was specified as the
8991 * first arg: dump that one service
8992 * - the first arg isn't the flattened component name of an existing service:
8993 * dump all services whose component contains the first arg as a substring
8994 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008995 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8996 int opti, boolean dumpAll) {
8997 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008999 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009000 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009001 try {
9002 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9003 for (UserInfo user : users) {
9004 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9005 services.add(r1);
9006 }
9007 }
9008 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009009 }
9010 }
9011 } else {
9012 ComponentName componentName = name != null
9013 ? ComponentName.unflattenFromString(name) : null;
9014 int objectId = 0;
9015 if (componentName == null) {
9016 // Not a '/' separated full component name; maybe an object ID?
9017 try {
9018 objectId = Integer.parseInt(name, 16);
9019 name = null;
9020 componentName = null;
9021 } catch (RuntimeException e) {
9022 }
9023 }
9024
9025 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009026 try {
9027 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9028 for (UserInfo user : users) {
9029 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9030 if (componentName != null) {
9031 if (r1.name.equals(componentName)) {
9032 services.add(r1);
9033 }
9034 } else if (name != null) {
9035 if (r1.name.flattenToString().contains(name)) {
9036 services.add(r1);
9037 }
9038 } else if (System.identityHashCode(r1) == objectId) {
9039 services.add(r1);
9040 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009041 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009042 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009043 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 }
9045 }
9046 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009047
9048 if (services.size() <= 0) {
9049 return false;
9050 }
9051
9052 boolean needSep = false;
9053 for (int i=0; i<services.size(); i++) {
9054 if (needSep) {
9055 pw.println();
9056 }
9057 needSep = true;
9058 dumpService("", fd, pw, services.get(i), args, dumpAll);
9059 }
9060 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 }
9062
9063 /**
9064 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9065 * there is a thread associated with the service.
9066 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009067 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9068 final ServiceRecord r, String[] args, boolean dumpAll) {
9069 String innerPrefix = prefix + " ";
9070 synchronized (this) {
9071 pw.print(prefix); pw.print("SERVICE ");
9072 pw.print(r.shortName); pw.print(" ");
9073 pw.print(Integer.toHexString(System.identityHashCode(r)));
9074 pw.print(" pid=");
9075 if (r.app != null) pw.println(r.app.pid);
9076 else pw.println("(not running)");
9077 if (dumpAll) {
9078 r.dump(pw, innerPrefix);
9079 }
9080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009082 pw.print(prefix); pw.println(" Client:");
9083 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009085 TransferPipe tp = new TransferPipe();
9086 try {
9087 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9088 tp.setBufferPrefix(prefix + " ");
9089 tp.go(fd);
9090 } finally {
9091 tp.kill();
9092 }
9093 } catch (IOException e) {
9094 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009095 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009096 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097 }
9098 }
9099 }
9100
Marco Nelissen18cb2872011-11-15 11:19:53 -08009101 /**
9102 * There are three ways to call this:
9103 * - no provider specified: dump all the providers
9104 * - a flattened component name that matched an existing provider was specified as the
9105 * first arg: dump that one provider
9106 * - the first arg isn't the flattened component name of an existing provider:
9107 * dump all providers whose component contains the first arg as a substring
9108 */
9109 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9110 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009111 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009112 }
9113
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009114 static class ItemMatcher {
9115 ArrayList<ComponentName> components;
9116 ArrayList<String> strings;
9117 ArrayList<Integer> objects;
9118 boolean all;
9119
9120 ItemMatcher() {
9121 all = true;
9122 }
9123
9124 void build(String name) {
9125 ComponentName componentName = ComponentName.unflattenFromString(name);
9126 if (componentName != null) {
9127 if (components == null) {
9128 components = new ArrayList<ComponentName>();
9129 }
9130 components.add(componentName);
9131 all = false;
9132 } else {
9133 int objectId = 0;
9134 // Not a '/' separated full component name; maybe an object ID?
9135 try {
9136 objectId = Integer.parseInt(name, 16);
9137 if (objects == null) {
9138 objects = new ArrayList<Integer>();
9139 }
9140 objects.add(objectId);
9141 all = false;
9142 } catch (RuntimeException e) {
9143 // Not an integer; just do string match.
9144 if (strings == null) {
9145 strings = new ArrayList<String>();
9146 }
9147 strings.add(name);
9148 all = false;
9149 }
9150 }
9151 }
9152
9153 int build(String[] args, int opti) {
9154 for (; opti<args.length; opti++) {
9155 String name = args[opti];
9156 if ("--".equals(name)) {
9157 return opti+1;
9158 }
9159 build(name);
9160 }
9161 return opti;
9162 }
9163
9164 boolean match(Object object, ComponentName comp) {
9165 if (all) {
9166 return true;
9167 }
9168 if (components != null) {
9169 for (int i=0; i<components.size(); i++) {
9170 if (components.get(i).equals(comp)) {
9171 return true;
9172 }
9173 }
9174 }
9175 if (objects != null) {
9176 for (int i=0; i<objects.size(); i++) {
9177 if (System.identityHashCode(object) == objects.get(i)) {
9178 return true;
9179 }
9180 }
9181 }
9182 if (strings != null) {
9183 String flat = comp.flattenToString();
9184 for (int i=0; i<strings.size(); i++) {
9185 if (flat.contains(strings.get(i))) {
9186 return true;
9187 }
9188 }
9189 }
9190 return false;
9191 }
9192 }
9193
Dianne Hackborn625ac272010-09-17 18:29:22 -07009194 /**
9195 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009196 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009197 * - the cmd arg isn't the flattened component name of an existing activity:
9198 * dump all activity whose component contains the cmd as a substring
9199 * - A hex number of the ActivityRecord object instance.
9200 */
9201 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9202 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009203 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009204
9205 if ("all".equals(name)) {
9206 synchronized (this) {
9207 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009208 activities.add(r1);
9209 }
9210 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009211 } else if ("top".equals(name)) {
9212 synchronized (this) {
9213 final int N = mMainStack.mHistory.size();
9214 if (N > 0) {
9215 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9216 }
9217 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009218 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009219 ItemMatcher matcher = new ItemMatcher();
9220 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009221
9222 synchronized (this) {
9223 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009224 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009225 activities.add(r1);
9226 }
9227 }
9228 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009229 }
9230
9231 if (activities.size() <= 0) {
9232 return false;
9233 }
9234
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009235 String[] newArgs = new String[args.length - opti];
9236 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9237
Dianne Hackborn30d71892010-12-11 10:37:55 -08009238 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009240 for (int i=activities.size()-1; i>=0; i--) {
9241 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009242 if (needSep) {
9243 pw.println();
9244 }
9245 needSep = true;
9246 synchronized (this) {
9247 if (lastTask != r.task) {
9248 lastTask = r.task;
9249 pw.print("TASK "); pw.print(lastTask.affinity);
9250 pw.print(" id="); pw.println(lastTask.taskId);
9251 if (dumpAll) {
9252 lastTask.dump(pw, " ");
9253 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009254 }
9255 }
9256 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009257 }
9258 return true;
9259 }
9260
9261 /**
9262 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9263 * there is a thread associated with the activity.
9264 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009265 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009266 final ActivityRecord r, String[] args, boolean dumpAll) {
9267 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009268 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009269 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9270 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9271 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009272 if (r.app != null) pw.println(r.app.pid);
9273 else pw.println("(not running)");
9274 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009275 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009276 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009277 }
9278 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009279 // flush anything that is already in the PrintWriter since the thread is going
9280 // to write to the file descriptor directly
9281 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009282 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009283 TransferPipe tp = new TransferPipe();
9284 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009285 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9286 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009287 tp.go(fd);
9288 } finally {
9289 tp.kill();
9290 }
9291 } catch (IOException e) {
9292 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009293 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009294 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009295 }
9296 }
9297 }
9298
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009299 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009300 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009301 boolean needSep = false;
9302
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009303 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009304 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009306 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 Iterator it = mRegisteredReceivers.values().iterator();
9308 while (it.hasNext()) {
9309 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 if (dumpPackage != null && (r.app == null ||
9311 !dumpPackage.equals(r.app.info.packageName))) {
9312 continue;
9313 }
9314 if (!printed) {
9315 pw.println(" Registered Receivers:");
9316 needSep = true;
9317 printed = true;
9318 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009319 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 r.dump(pw, " ");
9321 }
9322 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009323
9324 if (mReceiverResolver.dump(pw, needSep ?
9325 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9326 " ", dumpPackage, false)) {
9327 needSep = true;
9328 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009329 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009330
9331 for (BroadcastQueue q : mBroadcastQueues) {
9332 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009334
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009335 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009336
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009337 if (mStickyBroadcasts != null && dumpPackage == null) {
9338 if (needSep) {
9339 pw.println();
9340 }
9341 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009342 pw.println(" Sticky broadcasts:");
9343 StringBuilder sb = new StringBuilder(128);
9344 for (Map.Entry<String, ArrayList<Intent>> ent
9345 : mStickyBroadcasts.entrySet()) {
9346 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 if (dumpAll) {
9348 pw.println(":");
9349 ArrayList<Intent> intents = ent.getValue();
9350 final int N = intents.size();
9351 for (int i=0; i<N; i++) {
9352 sb.setLength(0);
9353 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009354 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009355 pw.println(sb.toString());
9356 Bundle bundle = intents.get(i).getExtras();
9357 if (bundle != null) {
9358 pw.print(" ");
9359 pw.println(bundle.toString());
9360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009361 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009362 } else {
9363 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364 }
9365 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009366 needSep = true;
9367 }
9368
9369 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009370 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009371 for (BroadcastQueue queue : mBroadcastQueues) {
9372 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9373 + queue.mBroadcastsScheduled);
9374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 pw.println(" mHandler:");
9376 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009379
9380 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 }
9382
Marco Nelissen18cb2872011-11-15 11:19:53 -08009383 /**
9384 * Prints a list of ServiceRecords (dumpsys activity services)
9385 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009386 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009387 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009390 ItemMatcher matcher = new ItemMatcher();
9391 matcher.build(args, opti);
9392
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009393 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009394 try {
9395 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9396 for (UserInfo user : users) {
9397 if (mServiceMap.getAllServices(user.id).size() > 0) {
9398 boolean printed = false;
9399 long nowReal = SystemClock.elapsedRealtime();
9400 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9401 user.id).iterator();
9402 needSep = false;
9403 while (it.hasNext()) {
9404 ServiceRecord r = it.next();
9405 if (!matcher.match(r, r.name)) {
9406 continue;
9407 }
9408 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9409 continue;
9410 }
9411 if (!printed) {
9412 pw.println(" Active services:");
9413 printed = true;
9414 }
9415 if (needSep) {
9416 pw.println();
9417 }
9418 pw.print(" * ");
9419 pw.println(r);
9420 if (dumpAll) {
9421 r.dump(pw, " ");
9422 needSep = true;
9423 } else {
9424 pw.print(" app=");
9425 pw.println(r.app);
9426 pw.print(" created=");
9427 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9428 pw.print(" started=");
9429 pw.print(r.startRequested);
9430 pw.print(" connections=");
9431 pw.println(r.connections.size());
9432 if (r.connections.size() > 0) {
9433 pw.println(" Connections:");
9434 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9435 for (int i = 0; i < clist.size(); i++) {
9436 ConnectionRecord conn = clist.get(i);
9437 pw.print(" ");
9438 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009439 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009440 pw.print(" -> ");
9441 ProcessRecord proc = conn.binding.client;
9442 pw.println(proc != null ? proc.toShortString() : "null");
9443 }
9444 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009445 }
9446 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009447 if (dumpClient && r.app != null && r.app.thread != null) {
9448 pw.println(" Client:");
9449 pw.flush();
9450 try {
9451 TransferPipe tp = new TransferPipe();
9452 try {
9453 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9454 r, args);
9455 tp.setBufferPrefix(" ");
9456 // Short timeout, since blocking here can
9457 // deadlock with the application.
9458 tp.go(fd, 2000);
9459 } finally {
9460 tp.kill();
9461 }
9462 } catch (IOException e) {
9463 pw.println(" Failure while dumping the service: " + e);
9464 } catch (RemoteException e) {
9465 pw.println(" Got a RemoteException while dumping the service");
9466 }
9467 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009468 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009469 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009470 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009473 } catch (RemoteException re) {
9474
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009477 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009478 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 for (int i=0; i<mPendingServices.size(); i++) {
9480 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009481 if (!matcher.match(r, r.name)) {
9482 continue;
9483 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009484 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9485 continue;
9486 }
9487 if (!printed) {
9488 if (needSep) pw.println(" ");
9489 needSep = true;
9490 pw.println(" Pending services:");
9491 printed = true;
9492 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009493 pw.print(" * Pending "); pw.println(r);
9494 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009495 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009496 needSep = true;
9497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009498
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009499 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009500 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009501 for (int i=0; i<mRestartingServices.size(); i++) {
9502 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009503 if (!matcher.match(r, r.name)) {
9504 continue;
9505 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009506 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9507 continue;
9508 }
9509 if (!printed) {
9510 if (needSep) pw.println(" ");
9511 needSep = true;
9512 pw.println(" Restarting services:");
9513 printed = true;
9514 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 pw.print(" * Restarting "); pw.println(r);
9516 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009518 needSep = true;
9519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009520
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009521 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009522 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 for (int i=0; i<mStoppingServices.size(); i++) {
9524 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009525 if (!matcher.match(r, r.name)) {
9526 continue;
9527 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009528 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9529 continue;
9530 }
9531 if (!printed) {
9532 if (needSep) pw.println(" ");
9533 needSep = true;
9534 pw.println(" Stopping services:");
9535 printed = true;
9536 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009537 pw.print(" * Stopping "); pw.println(r);
9538 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009539 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009540 needSep = true;
9541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009543 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009545 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009546 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547 = mServiceConnections.values().iterator();
9548 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009549 ArrayList<ConnectionRecord> r = it.next();
9550 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009551 ConnectionRecord cr = r.get(i);
9552 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9553 continue;
9554 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009555 if (dumpPackage != null && (cr.binding.client == null
9556 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9557 continue;
9558 }
9559 if (!printed) {
9560 if (needSep) pw.println(" ");
9561 needSep = true;
9562 pw.println(" Connection bindings to services:");
9563 printed = true;
9564 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009565 pw.print(" * "); pw.println(cr);
9566 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009568 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009569 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570 }
9571 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009572
9573 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 }
9575
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009576 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009577 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009578 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009580 ItemMatcher matcher = new ItemMatcher();
9581 matcher.build(args, opti);
9582
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009583 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009584
9585 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009586
9587 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009588 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009589 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009590 ContentProviderRecord r = mLaunchingProviders.get(i);
9591 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9592 continue;
9593 }
9594 if (!printed) {
9595 if (needSep) pw.println(" ");
9596 needSep = true;
9597 pw.println(" Launching content providers:");
9598 printed = true;
9599 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009600 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009601 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009602 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009603 }
9604
9605 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009606 if (needSep) pw.println();
9607 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009608 pw.println("Granted Uri Permissions:");
9609 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9610 int uid = mGrantedUriPermissions.keyAt(i);
9611 HashMap<Uri, UriPermission> perms
9612 = mGrantedUriPermissions.valueAt(i);
9613 pw.print(" * UID "); pw.print(uid);
9614 pw.println(" holds:");
9615 for (UriPermission perm : perms.values()) {
9616 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009617 if (dumpAll) {
9618 perm.dump(pw, " ");
9619 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009620 }
9621 }
9622 needSep = true;
9623 }
9624
9625 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009626 }
9627
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009628 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009629 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009630 boolean needSep = false;
9631
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009632 if (mIntentSenderRecords.size() > 0) {
9633 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009634 Iterator<WeakReference<PendingIntentRecord>> it
9635 = mIntentSenderRecords.values().iterator();
9636 while (it.hasNext()) {
9637 WeakReference<PendingIntentRecord> ref = it.next();
9638 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009639 if (dumpPackage != null && (rec == null
9640 || !dumpPackage.equals(rec.key.packageName))) {
9641 continue;
9642 }
9643 if (!printed) {
9644 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9645 printed = true;
9646 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009647 needSep = true;
9648 if (rec != null) {
9649 pw.print(" * "); pw.println(rec);
9650 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009651 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009652 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009653 } else {
9654 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655 }
9656 }
9657 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009658
9659 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 }
9661
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009662 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009663 String prefix, String label, boolean complete, boolean brief, boolean client,
9664 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009666 boolean needNL = false;
9667 final String innerPrefix = prefix + " ";
9668 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009670 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009671 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9672 continue;
9673 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009674 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009675 if (needNL) {
9676 pw.println(" ");
9677 needNL = false;
9678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 if (lastTask != r.task) {
9680 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009681 pw.print(prefix);
9682 pw.print(full ? "* " : " ");
9683 pw.println(lastTask);
9684 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009685 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009686 } else if (complete) {
9687 // Complete + brief == give a summary. Isn't that obvious?!?
9688 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009689 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009690 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009691 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009694 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9695 pw.print(" #"); pw.print(i); pw.print(": ");
9696 pw.println(r);
9697 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009698 r.dump(pw, innerPrefix);
9699 } else if (complete) {
9700 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009701 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009702 if (r.app != null) {
9703 pw.print(innerPrefix); pw.println(r.app);
9704 }
9705 }
9706 if (client && r.app != null && r.app.thread != null) {
9707 // flush anything that is already in the PrintWriter since the thread is going
9708 // to write to the file descriptor directly
9709 pw.flush();
9710 try {
9711 TransferPipe tp = new TransferPipe();
9712 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009713 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9714 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009715 // Short timeout, since blocking here can
9716 // deadlock with the application.
9717 tp.go(fd, 2000);
9718 } finally {
9719 tp.kill();
9720 }
9721 } catch (IOException e) {
9722 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9723 } catch (RemoteException e) {
9724 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9725 }
9726 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009728 }
9729 }
9730
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009731 private static String buildOomTag(String prefix, String space, int val, int base) {
9732 if (val == base) {
9733 if (space == null) return prefix;
9734 return prefix + " ";
9735 }
9736 return prefix + "+" + Integer.toString(val-base);
9737 }
9738
9739 private static final int dumpProcessList(PrintWriter pw,
9740 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009741 String prefix, String normalLabel, String persistentLabel,
9742 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009744 final int N = list.size()-1;
9745 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009747 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9748 continue;
9749 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009750 pw.println(String.format("%s%s #%2d: %s",
9751 prefix, (r.persistent ? persistentLabel : normalLabel),
9752 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 if (r.persistent) {
9754 numPers++;
9755 }
9756 }
9757 return numPers;
9758 }
9759
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009760 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009761 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009762 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009763 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009764
Dianne Hackborn905577f2011-09-07 18:31:28 -07009765 ArrayList<Pair<ProcessRecord, Integer>> list
9766 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9767 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009768 ProcessRecord r = origList.get(i);
9769 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9770 continue;
9771 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009772 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9773 }
9774
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009775 if (list.size() <= 0) {
9776 return false;
9777 }
9778
Dianne Hackborn905577f2011-09-07 18:31:28 -07009779 Comparator<Pair<ProcessRecord, Integer>> comparator
9780 = new Comparator<Pair<ProcessRecord, Integer>>() {
9781 @Override
9782 public int compare(Pair<ProcessRecord, Integer> object1,
9783 Pair<ProcessRecord, Integer> object2) {
9784 if (object1.first.setAdj != object2.first.setAdj) {
9785 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9786 }
9787 if (object1.second.intValue() != object2.second.intValue()) {
9788 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9789 }
9790 return 0;
9791 }
9792 };
9793
9794 Collections.sort(list, comparator);
9795
Dianne Hackborn287952c2010-09-22 22:34:31 -07009796 final long curRealtime = SystemClock.elapsedRealtime();
9797 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9798 final long curUptime = SystemClock.uptimeMillis();
9799 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9800
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009801 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009802 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009803 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009804 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009805 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009806 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9807 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009808 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9809 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009810 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9811 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009812 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9813 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009814 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009815 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009816 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9817 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9818 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9819 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9820 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9821 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9822 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9823 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009824 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9825 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009826 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9827 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009828 } else {
9829 oomAdj = Integer.toString(r.setAdj);
9830 }
9831 String schedGroup;
9832 switch (r.setSchedGroup) {
9833 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9834 schedGroup = "B";
9835 break;
9836 case Process.THREAD_GROUP_DEFAULT:
9837 schedGroup = "F";
9838 break;
9839 default:
9840 schedGroup = Integer.toString(r.setSchedGroup);
9841 break;
9842 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009843 String foreground;
9844 if (r.foregroundActivities) {
9845 foreground = "A";
9846 } else if (r.foregroundServices) {
9847 foreground = "S";
9848 } else {
9849 foreground = " ";
9850 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009851 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009852 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009853 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9854 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009855 if (r.adjSource != null || r.adjTarget != null) {
9856 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009857 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009858 if (r.adjTarget instanceof ComponentName) {
9859 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9860 } else if (r.adjTarget != null) {
9861 pw.print(r.adjTarget.toString());
9862 } else {
9863 pw.print("{null}");
9864 }
9865 pw.print("<=");
9866 if (r.adjSource instanceof ProcessRecord) {
9867 pw.print("Proc{");
9868 pw.print(((ProcessRecord)r.adjSource).toShortString());
9869 pw.println("}");
9870 } else if (r.adjSource != null) {
9871 pw.println(r.adjSource.toString());
9872 } else {
9873 pw.println("{null}");
9874 }
9875 }
9876 if (inclDetails) {
9877 pw.print(prefix);
9878 pw.print(" ");
9879 pw.print("oom: max="); pw.print(r.maxAdj);
9880 pw.print(" hidden="); pw.print(r.hiddenAdj);
9881 pw.print(" curRaw="); pw.print(r.curRawAdj);
9882 pw.print(" setRaw="); pw.print(r.setRawAdj);
9883 pw.print(" cur="); pw.print(r.curAdj);
9884 pw.print(" set="); pw.println(r.setAdj);
9885 pw.print(prefix);
9886 pw.print(" ");
9887 pw.print("keeping="); pw.print(r.keeping);
9888 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009889 pw.print(" empty="); pw.print(r.empty);
9890 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009891
9892 if (!r.keeping) {
9893 if (r.lastWakeTime != 0) {
9894 long wtime;
9895 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9896 synchronized (stats) {
9897 wtime = stats.getProcessWakeTime(r.info.uid,
9898 r.pid, curRealtime);
9899 }
9900 long timeUsed = wtime - r.lastWakeTime;
9901 pw.print(prefix);
9902 pw.print(" ");
9903 pw.print("keep awake over ");
9904 TimeUtils.formatDuration(realtimeSince, pw);
9905 pw.print(" used ");
9906 TimeUtils.formatDuration(timeUsed, pw);
9907 pw.print(" (");
9908 pw.print((timeUsed*100)/realtimeSince);
9909 pw.println("%)");
9910 }
9911 if (r.lastCpuTime != 0) {
9912 long timeUsed = r.curCpuTime - r.lastCpuTime;
9913 pw.print(prefix);
9914 pw.print(" ");
9915 pw.print("run cpu over ");
9916 TimeUtils.formatDuration(uptimeSince, pw);
9917 pw.print(" used ");
9918 TimeUtils.formatDuration(timeUsed, pw);
9919 pw.print(" (");
9920 pw.print((timeUsed*100)/uptimeSince);
9921 pw.println("%)");
9922 }
9923 }
9924 }
9925 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009926 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009927 }
9928
Dianne Hackbornb437e092011-08-05 17:50:29 -07009929 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009930 ArrayList<ProcessRecord> procs;
9931 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009932 if (args != null && args.length > start
9933 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009934 procs = new ArrayList<ProcessRecord>();
9935 int pid = -1;
9936 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009937 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009938 } catch (NumberFormatException e) {
9939
9940 }
9941 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9942 ProcessRecord proc = mLruProcesses.get(i);
9943 if (proc.pid == pid) {
9944 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009945 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009946 procs.add(proc);
9947 }
9948 }
9949 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009950 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009951 return null;
9952 }
9953 } else {
9954 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9955 }
9956 }
9957 return procs;
9958 }
9959
9960 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9961 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009962 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009963 if (procs == null) {
9964 return;
9965 }
9966
9967 long uptime = SystemClock.uptimeMillis();
9968 long realtime = SystemClock.elapsedRealtime();
9969 pw.println("Applications Graphics Acceleration Info:");
9970 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9971
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009972 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9973 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009974 if (r.thread != null) {
9975 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9976 pw.flush();
9977 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009978 TransferPipe tp = new TransferPipe();
9979 try {
9980 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9981 tp.go(fd);
9982 } finally {
9983 tp.kill();
9984 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009985 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009986 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009987 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009988 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009989 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009990 pw.flush();
9991 }
9992 }
9993 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009994 }
9995
Jeff Brown6754ba22011-12-14 20:20:01 -08009996 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9997 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9998 if (procs == null) {
9999 return;
10000 }
10001
10002 pw.println("Applications Database Info:");
10003
10004 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10005 ProcessRecord r = procs.get(i);
10006 if (r.thread != null) {
10007 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10008 pw.flush();
10009 try {
10010 TransferPipe tp = new TransferPipe();
10011 try {
10012 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10013 tp.go(fd);
10014 } finally {
10015 tp.kill();
10016 }
10017 } catch (IOException e) {
10018 pw.println("Failure while dumping the app: " + r);
10019 pw.flush();
10020 } catch (RemoteException e) {
10021 pw.println("Got a RemoteException while dumping the app " + r);
10022 pw.flush();
10023 }
10024 }
10025 }
10026 }
10027
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010028 final static class MemItem {
10029 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010030 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010031 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010032 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010033 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010034
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010035 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010036 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010037 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010038 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010039 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010040 }
10041 }
10042
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010043 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010044 boolean sort) {
10045 if (sort) {
10046 Collections.sort(items, new Comparator<MemItem>() {
10047 @Override
10048 public int compare(MemItem lhs, MemItem rhs) {
10049 if (lhs.pss < rhs.pss) {
10050 return 1;
10051 } else if (lhs.pss > rhs.pss) {
10052 return -1;
10053 }
10054 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010055 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010056 });
10057 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010058
10059 for (int i=0; i<items.size(); i++) {
10060 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010061 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010062 if (mi.subitems != null) {
10063 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10064 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010065 }
10066 }
10067
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010068 // These are in KB.
10069 static final long[] DUMP_MEM_BUCKETS = new long[] {
10070 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10071 120*1024, 160*1024, 200*1024,
10072 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10073 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10074 };
10075
Dianne Hackborn672342c2011-11-29 11:29:02 -080010076 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10077 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010078 int start = label.lastIndexOf('.');
10079 if (start >= 0) start++;
10080 else start = 0;
10081 int end = label.length();
10082 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10083 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10084 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10085 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010086 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010087 out.append(label, start, end);
10088 return;
10089 }
10090 }
10091 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010092 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010093 out.append(label, start, end);
10094 }
10095
10096 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10097 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10098 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10099 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10100 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10101 };
10102 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10103 "System", "Persistent", "Foreground",
10104 "Visible", "Perceptible", "Heavy Weight",
10105 "Backup", "A Services", "Home", "Previous",
10106 "B Services", "Background"
10107 };
10108
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010109 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010110 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010111 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010112 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010113 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010114
10115 int opti = 0;
10116 while (opti < args.length) {
10117 String opt = args[opti];
10118 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10119 break;
10120 }
10121 opti++;
10122 if ("-a".equals(opt)) {
10123 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010124 } else if ("--oom".equals(opt)) {
10125 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010126 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010127 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010128 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010129 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010130 pw.println("If [process] is specified it can be the name or ");
10131 pw.println("pid of a specific process to dump.");
10132 return;
10133 } else {
10134 pw.println("Unknown argument: " + opt + "; use -h for help");
10135 }
10136 }
10137
10138 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010139 if (procs == null) {
10140 return;
10141 }
10142
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010143 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010144 long uptime = SystemClock.uptimeMillis();
10145 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010146
10147 if (procs.size() == 1 || isCheckinRequest) {
10148 dumpAll = true;
10149 }
10150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010151 if (isCheckinRequest) {
10152 // short checkin version
10153 pw.println(uptime + "," + realtime);
10154 pw.flush();
10155 } else {
10156 pw.println("Applications Memory Usage (kB):");
10157 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10158 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010159
Dianne Hackbornb437e092011-08-05 17:50:29 -070010160 String[] innerArgs = new String[args.length-opti];
10161 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10162
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010163 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10164 long nativePss=0, dalvikPss=0, otherPss=0;
10165 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10166
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010167 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10168 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10169 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010170
10171 long totalPss = 0;
10172
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010173 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10174 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010175 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010176 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010177 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10178 pw.flush();
10179 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010180 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010181 if (dumpAll) {
10182 try {
10183 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10184 } catch (RemoteException e) {
10185 if (!isCheckinRequest) {
10186 pw.println("Got RemoteException!");
10187 pw.flush();
10188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010189 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010190 } else {
10191 mi = new Debug.MemoryInfo();
10192 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010194
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010195 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010196 long myTotalPss = mi.getTotalPss();
10197 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010198 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010199 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010200 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010201
10202 nativePss += mi.nativePss;
10203 dalvikPss += mi.dalvikPss;
10204 otherPss += mi.otherPss;
10205 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10206 long mem = mi.getOtherPss(j);
10207 miscPss[j] += mem;
10208 otherPss -= mem;
10209 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010210
10211 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010212 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10213 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010214 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010215 if (oomProcs[oomIndex] == null) {
10216 oomProcs[oomIndex] = new ArrayList<MemItem>();
10217 }
10218 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010219 break;
10220 }
10221 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010223 }
10224 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010225
10226 if (!isCheckinRequest && procs.size() > 1) {
10227 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10228
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010229 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10230 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10231 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010232 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010233 String label = Debug.MemoryInfo.getOtherLabel(j);
10234 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010235 }
10236
Dianne Hackbornb437e092011-08-05 17:50:29 -070010237 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10238 for (int j=0; j<oomPss.length; j++) {
10239 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010240 String label = DUMP_MEM_OOM_LABEL[j];
10241 MemItem item = new MemItem(label, label, oomPss[j],
10242 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010243 item.subitems = oomProcs[j];
10244 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010245 }
10246 }
10247
Dianne Hackborn672342c2011-11-29 11:29:02 -080010248 if (outTag != null || outStack != null) {
10249 if (outTag != null) {
10250 appendMemBucket(outTag, totalPss, "total", false);
10251 }
10252 if (outStack != null) {
10253 appendMemBucket(outStack, totalPss, "total", true);
10254 }
10255 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010256 for (int i=0; i<oomMems.size(); i++) {
10257 MemItem miCat = oomMems.get(i);
10258 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10259 continue;
10260 }
10261 if (miCat.id < ProcessList.SERVICE_ADJ
10262 || miCat.id == ProcessList.HOME_APP_ADJ
10263 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010264 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10265 outTag.append(" / ");
10266 }
10267 if (outStack != null) {
10268 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10269 if (firstLine) {
10270 outStack.append(":");
10271 firstLine = false;
10272 }
10273 outStack.append("\n\t at ");
10274 } else {
10275 outStack.append("$");
10276 }
10277 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010278 for (int j=0; j<miCat.subitems.size(); j++) {
10279 MemItem mi = miCat.subitems.get(j);
10280 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010281 if (outTag != null) {
10282 outTag.append(" ");
10283 }
10284 if (outStack != null) {
10285 outStack.append("$");
10286 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010287 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010288 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10289 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10290 }
10291 if (outStack != null) {
10292 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10293 }
10294 }
10295 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10296 outStack.append("(");
10297 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10298 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10299 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10300 outStack.append(":");
10301 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10302 }
10303 }
10304 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010305 }
10306 }
10307 }
10308 }
10309
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010310 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010311 pw.println();
10312 pw.println("Total PSS by process:");
10313 dumpMemItems(pw, " ", procMems, true);
10314 pw.println();
10315 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010316 pw.println("Total PSS by OOM adjustment:");
10317 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010318 if (!oomOnly) {
10319 PrintWriter out = categoryPw != null ? categoryPw : pw;
10320 out.println();
10321 out.println("Total PSS by category:");
10322 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010323 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010324 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010325 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010326 final int[] SINGLE_LONG_FORMAT = new int[] {
10327 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10328 };
10329 long[] longOut = new long[1];
10330 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10331 SINGLE_LONG_FORMAT, null, longOut, null);
10332 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10333 longOut[0] = 0;
10334 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10335 SINGLE_LONG_FORMAT, null, longOut, null);
10336 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10337 longOut[0] = 0;
10338 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10339 SINGLE_LONG_FORMAT, null, longOut, null);
10340 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10341 longOut[0] = 0;
10342 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10343 SINGLE_LONG_FORMAT, null, longOut, null);
10344 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10345 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10346 pw.print(shared); pw.println(" kB");
10347 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10348 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010350 }
10351
10352 /**
10353 * Searches array of arguments for the specified string
10354 * @param args array of argument strings
10355 * @param value value to search for
10356 * @return true if the value is contained in the array
10357 */
10358 private static boolean scanArgs(String[] args, String value) {
10359 if (args != null) {
10360 for (String arg : args) {
10361 if (value.equals(arg)) {
10362 return true;
10363 }
10364 }
10365 }
10366 return false;
10367 }
10368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010369 private final void killServicesLocked(ProcessRecord app,
10370 boolean allowRestart) {
10371 // Report disconnected services.
10372 if (false) {
10373 // XXX we are letting the client link to the service for
10374 // death notifications.
10375 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010376 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010377 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010378 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010379 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010380 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 = r.connections.values().iterator();
10382 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010383 ArrayList<ConnectionRecord> cl = jt.next();
10384 for (int i=0; i<cl.size(); i++) {
10385 ConnectionRecord c = cl.get(i);
10386 if (c.binding.client != app) {
10387 try {
10388 //c.conn.connected(r.className, null);
10389 } catch (Exception e) {
10390 // todo: this should be asynchronous!
10391 Slog.w(TAG, "Exception thrown disconnected servce "
10392 + r.shortName
10393 + " from app " + app.processName, e);
10394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010395 }
10396 }
10397 }
10398 }
10399 }
10400 }
10401 }
10402
10403 // Clean up any connections this application has to other services.
10404 if (app.connections.size() > 0) {
10405 Iterator<ConnectionRecord> it = app.connections.iterator();
10406 while (it.hasNext()) {
10407 ConnectionRecord r = it.next();
10408 removeConnectionLocked(r, app, null);
10409 }
10410 }
10411 app.connections.clear();
10412
10413 if (app.services.size() != 0) {
10414 // Any services running in the application need to be placed
10415 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010416 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010417 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010418 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010419 synchronized (sr.stats.getBatteryStats()) {
10420 sr.stats.stopLaunchedLocked();
10421 }
10422 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010423 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010425 if (mStoppingServices.remove(sr)) {
10426 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10427 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010428
10429 boolean hasClients = sr.bindings.size() > 0;
10430 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010431 Iterator<IntentBindRecord> bindings
10432 = sr.bindings.values().iterator();
10433 while (bindings.hasNext()) {
10434 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010435 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010436 + ": shouldUnbind=" + b.hasBound);
10437 b.binder = null;
10438 b.requested = b.received = b.hasBound = false;
10439 }
10440 }
10441
Dianne Hackborn070783f2010-12-29 16:46:28 -080010442 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10443 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010444 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010445 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010446 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010447 sr.crashCount, sr.shortName, app.pid);
10448 bringDownServiceLocked(sr, true);
10449 } else if (!allowRestart) {
10450 bringDownServiceLocked(sr, true);
10451 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010452 boolean canceled = scheduleServiceRestartLocked(sr, true);
10453
10454 // Should the service remain running? Note that in the
10455 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010456 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010457 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10458 if (sr.pendingStarts.size() == 0) {
10459 sr.startRequested = false;
10460 if (!hasClients) {
10461 // Whoops, no reason to restart!
10462 bringDownServiceLocked(sr, true);
10463 }
10464 }
10465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010466 }
10467 }
10468
10469 if (!allowRestart) {
10470 app.services.clear();
10471 }
10472 }
10473
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010474 // Make sure we have no more records on the stopping list.
10475 int i = mStoppingServices.size();
10476 while (i > 0) {
10477 i--;
10478 ServiceRecord sr = mStoppingServices.get(i);
10479 if (sr.app == app) {
10480 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010481 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010482 }
10483 }
10484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010485 app.executingServices.clear();
10486 }
10487
10488 private final void removeDyingProviderLocked(ProcessRecord proc,
10489 ContentProviderRecord cpr) {
10490 synchronized (cpr) {
10491 cpr.launchingApp = null;
10492 cpr.notifyAll();
10493 }
10494
Amith Yamasani742a6712011-05-04 14:49:28 -070010495 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010496 String names[] = cpr.info.authority.split(";");
10497 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010498 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499 }
10500
10501 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10502 while (cit.hasNext()) {
10503 ProcessRecord capp = cit.next();
10504 if (!capp.persistent && capp.thread != null
10505 && capp.pid != 0
10506 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010507 Slog.i(TAG, "Kill " + capp.processName
10508 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010509 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010510 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010511 capp.processName, capp.setAdj, "dying provider "
10512 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010513 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 }
10515 }
10516
10517 mLaunchingProviders.remove(cpr);
10518 }
10519
10520 /**
10521 * Main code for cleaning up a process when it has gone away. This is
10522 * called both as a result of the process dying, or directly when stopping
10523 * a process when running in single process mode.
10524 */
10525 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010526 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010527 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010528 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 }
10530
Dianne Hackborn36124872009-10-08 16:22:03 -070010531 mProcessesToGc.remove(app);
10532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 // Dismiss any open dialogs.
10534 if (app.crashDialog != null) {
10535 app.crashDialog.dismiss();
10536 app.crashDialog = null;
10537 }
10538 if (app.anrDialog != null) {
10539 app.anrDialog.dismiss();
10540 app.anrDialog = null;
10541 }
10542 if (app.waitDialog != null) {
10543 app.waitDialog.dismiss();
10544 app.waitDialog = null;
10545 }
10546
10547 app.crashing = false;
10548 app.notResponding = false;
10549
10550 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010551 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010552 app.thread = null;
10553 app.forcingToForeground = null;
10554 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010555 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010556 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010557 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010558
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010559 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010560
10561 boolean restart = false;
10562
10563 int NL = mLaunchingProviders.size();
10564
10565 // Remove published content providers.
10566 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010567 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010568 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010569 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010571 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572
10573 // See if someone is waiting for this provider... in which
10574 // case we don't remove it, but just let it restart.
10575 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010576 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 for (; i<NL; i++) {
10578 if (mLaunchingProviders.get(i) == cpr) {
10579 restart = true;
10580 break;
10581 }
10582 }
10583 } else {
10584 i = NL;
10585 }
10586
10587 if (i >= NL) {
10588 removeDyingProviderLocked(app, cpr);
10589 NL = mLaunchingProviders.size();
10590 }
10591 }
10592 app.pubProviders.clear();
10593 }
10594
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010595 // Take care of any launching providers waiting for this process.
10596 if (checkAppInLaunchingProvidersLocked(app, false)) {
10597 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 // Unregister from connected content providers.
10601 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010602 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010603 while (it.hasNext()) {
10604 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10605 cpr.clients.remove(app);
10606 }
10607 app.conProviders.clear();
10608 }
10609
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010610 // At this point there may be remaining entries in mLaunchingProviders
10611 // where we were the only one waiting, so they are no longer of use.
10612 // Look for these and clean up if found.
10613 // XXX Commented out for now. Trying to figure out a way to reproduce
10614 // the actual situation to identify what is actually going on.
10615 if (false) {
10616 for (int i=0; i<NL; i++) {
10617 ContentProviderRecord cpr = (ContentProviderRecord)
10618 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010619 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010620 synchronized (cpr) {
10621 cpr.launchingApp = null;
10622 cpr.notifyAll();
10623 }
10624 }
10625 }
10626 }
10627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 skipCurrentReceiverLocked(app);
10629
10630 // Unregister any receivers.
10631 if (app.receivers.size() > 0) {
10632 Iterator<ReceiverList> it = app.receivers.iterator();
10633 while (it.hasNext()) {
10634 removeReceiverLocked(it.next());
10635 }
10636 app.receivers.clear();
10637 }
10638
Christopher Tate181fafa2009-05-14 11:12:14 -070010639 // If the app is undergoing backup, tell the backup manager about it
10640 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010641 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010642 try {
10643 IBackupManager bm = IBackupManager.Stub.asInterface(
10644 ServiceManager.getService(Context.BACKUP_SERVICE));
10645 bm.agentDisconnected(app.info.packageName);
10646 } catch (RemoteException e) {
10647 // can't happen; backup manager is local
10648 }
10649 }
10650
Jeff Sharkey287bd832011-05-28 19:36:26 -070010651 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 // If the caller is restarting this app, then leave it in its
10654 // current lists and let the caller take care of it.
10655 if (restarting) {
10656 return;
10657 }
10658
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010659 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010660 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010661 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010662 mProcessNames.remove(app.processName, app.uid);
10663 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010664 if (mHeavyWeightProcess == app) {
10665 mHeavyWeightProcess = null;
10666 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 } else if (!app.removed) {
10669 // This app is persistent, so we need to keep its record around.
10670 // If it is not already on the pending app list, add it there
10671 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010672 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10673 mPersistentStartingProcesses.add(app);
10674 restart = true;
10675 }
10676 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010677 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10678 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010679 mProcessesOnHold.remove(app);
10680
The Android Open Source Project4df24232009-03-05 14:34:35 -080010681 if (app == mHomeProcess) {
10682 mHomeProcess = null;
10683 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010684 if (app == mPreviousProcess) {
10685 mPreviousProcess = null;
10686 }
10687
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010688 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 // We have components that still need to be running in the
10690 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010691 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010692 startProcessLocked(app, "restart", app.processName);
10693 } else if (app.pid > 0 && app.pid != MY_PID) {
10694 // Goodbye!
10695 synchronized (mPidsSelfLocked) {
10696 mPidsSelfLocked.remove(app.pid);
10697 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10698 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010699 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 }
10701 }
10702
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010703 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10704 // Look through the content providers we are waiting to have launched,
10705 // and if any run in this process then either schedule a restart of
10706 // the process or kill the client waiting for it if this process has
10707 // gone bad.
10708 int NL = mLaunchingProviders.size();
10709 boolean restart = false;
10710 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010711 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010712 if (cpr.launchingApp == app) {
10713 if (!alwaysBad && !app.bad) {
10714 restart = true;
10715 } else {
10716 removeDyingProviderLocked(app, cpr);
10717 NL = mLaunchingProviders.size();
10718 }
10719 }
10720 }
10721 return restart;
10722 }
10723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010724 // =========================================================
10725 // SERVICES
10726 // =========================================================
10727
10728 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10729 ActivityManager.RunningServiceInfo info =
10730 new ActivityManager.RunningServiceInfo();
10731 info.service = r.name;
10732 if (r.app != null) {
10733 info.pid = r.app.pid;
10734 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010735 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 info.process = r.processName;
10737 info.foreground = r.isForeground;
10738 info.activeSince = r.createTime;
10739 info.started = r.startRequested;
10740 info.clientCount = r.connections.size();
10741 info.crashCount = r.crashCount;
10742 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010743 if (r.isForeground) {
10744 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10745 }
10746 if (r.startRequested) {
10747 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10748 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010749 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010750 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10751 }
10752 if (r.app != null && r.app.persistent) {
10753 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10754 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010755
10756 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10757 for (int i=0; i<connl.size(); i++) {
10758 ConnectionRecord conn = connl.get(i);
10759 if (conn.clientLabel != 0) {
10760 info.clientPackage = conn.binding.client.info.packageName;
10761 info.clientLabel = conn.clientLabel;
10762 return info;
10763 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010764 }
10765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 return info;
10767 }
10768
10769 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10770 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010771 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 synchronized (this) {
10773 ArrayList<ActivityManager.RunningServiceInfo> res
10774 = new ArrayList<ActivityManager.RunningServiceInfo>();
10775
Amith Yamasani742a6712011-05-04 14:49:28 -070010776 int userId = UserId.getUserId(Binder.getCallingUid());
10777 if (mServiceMap.getAllServices(userId).size() > 0) {
10778 Iterator<ServiceRecord> it
10779 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010780 while (it.hasNext() && res.size() < maxNum) {
10781 res.add(makeRunningServiceInfoLocked(it.next()));
10782 }
10783 }
10784
10785 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10786 ServiceRecord r = mRestartingServices.get(i);
10787 ActivityManager.RunningServiceInfo info =
10788 makeRunningServiceInfoLocked(r);
10789 info.restarting = r.nextRestartTime;
10790 res.add(info);
10791 }
10792
10793 return res;
10794 }
10795 }
10796
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010797 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010798 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010799 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010800 int userId = UserId.getUserId(Binder.getCallingUid());
10801 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010802 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010803 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10804 for (int i=0; i<conn.size(); i++) {
10805 if (conn.get(i).clientIntent != null) {
10806 return conn.get(i).clientIntent;
10807 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010808 }
10809 }
10810 }
10811 }
10812 return null;
10813 }
10814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010815 private final ServiceRecord findServiceLocked(ComponentName name,
10816 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010817 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 return r == token ? r : null;
10819 }
10820
10821 private final class ServiceLookupResult {
10822 final ServiceRecord record;
10823 final String permission;
10824
10825 ServiceLookupResult(ServiceRecord _record, String _permission) {
10826 record = _record;
10827 permission = _permission;
10828 }
10829 };
10830
10831 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010832 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 ServiceRecord r = null;
10834 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010835 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 }
10837 if (r == null) {
10838 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010839 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 }
10841
10842 if (r == null) {
10843 try {
10844 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010845 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010846 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 ServiceInfo sInfo =
10848 rInfo != null ? rInfo.serviceInfo : null;
10849 if (sInfo == null) {
10850 return null;
10851 }
10852
10853 ComponentName name = new ComponentName(
10854 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010855 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 } catch (RemoteException ex) {
10857 // pm is in same process, this will never happen.
10858 }
10859 }
10860 if (r != null) {
10861 int callingPid = Binder.getCallingPid();
10862 int callingUid = Binder.getCallingUid();
10863 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010864 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010866 if (!r.exported) {
10867 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10868 + " from pid=" + callingPid
10869 + ", uid=" + callingUid
10870 + " that is not exported from uid " + r.appInfo.uid);
10871 return new ServiceLookupResult(null, "not exported from uid "
10872 + r.appInfo.uid);
10873 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010874 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 + " from pid=" + callingPid
10876 + ", uid=" + callingUid
10877 + " requires " + r.permission);
10878 return new ServiceLookupResult(null, r.permission);
10879 }
10880 return new ServiceLookupResult(r, null);
10881 }
10882 return null;
10883 }
10884
10885 private class ServiceRestarter implements Runnable {
10886 private ServiceRecord mService;
10887
10888 void setService(ServiceRecord service) {
10889 mService = service;
10890 }
10891
10892 public void run() {
10893 synchronized(ActivityManagerService.this) {
10894 performServiceRestartLocked(mService);
10895 }
10896 }
10897 }
10898
10899 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010900 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010902 if (DEBUG_SERVICE)
10903 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010904 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010906 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010907 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010908 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010909 if (r == null) {
10910 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010911 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010913 if (r == null) {
10914 try {
10915 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010916 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010917 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010918 ServiceInfo sInfo =
10919 rInfo != null ? rInfo.serviceInfo : null;
10920 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010921 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 ": not found");
10923 return null;
10924 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010925 if (userId > 0) {
10926 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 ComponentName name = new ComponentName(
10929 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010930 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010931 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010932 Intent.FilterComparison filter = new Intent.FilterComparison(
10933 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 ServiceRestarter res = new ServiceRestarter();
10935 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10936 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10937 synchronized (stats) {
10938 ss = stats.getServiceStatsLocked(
10939 sInfo.applicationInfo.uid, sInfo.packageName,
10940 sInfo.name);
10941 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010942 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010943 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010944 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10945 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010946
10947 // Make sure this component isn't in the pending list.
10948 int N = mPendingServices.size();
10949 for (int i=0; i<N; i++) {
10950 ServiceRecord pr = mPendingServices.get(i);
10951 if (pr.name.equals(name)) {
10952 mPendingServices.remove(i);
10953 i--;
10954 N--;
10955 }
10956 }
10957 }
10958 } catch (RemoteException ex) {
10959 // pm is in same process, this will never happen.
10960 }
10961 }
10962 if (r != null) {
10963 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010964 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010966 if (!r.exported) {
10967 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10968 + " from pid=" + callingPid
10969 + ", uid=" + callingUid
10970 + " that is not exported from uid " + r.appInfo.uid);
10971 return new ServiceLookupResult(null, "not exported from uid "
10972 + r.appInfo.uid);
10973 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010974 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010975 + " from pid=" + callingPid
10976 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 + " requires " + r.permission);
10978 return new ServiceLookupResult(null, r.permission);
10979 }
10980 return new ServiceLookupResult(r, null);
10981 }
10982 return null;
10983 }
10984
Dianne Hackborn287952c2010-09-22 22:34:31 -070010985 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10986 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10987 + why + " of " + r + " in app " + r.app);
10988 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10989 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990 long now = SystemClock.uptimeMillis();
10991 if (r.executeNesting == 0 && r.app != null) {
10992 if (r.app.executingServices.size() == 0) {
10993 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10994 msg.obj = r.app;
10995 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10996 }
10997 r.app.executingServices.add(r);
10998 }
10999 r.executeNesting++;
11000 r.executingStart = now;
11001 }
11002
11003 private final void sendServiceArgsLocked(ServiceRecord r,
11004 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011005 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011006 if (N == 0) {
11007 return;
11008 }
11009
Dianne Hackborn39792d22010-08-19 18:01:52 -070011010 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011012 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011013 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11014 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011015 if (si.intent == null && N > 1) {
11016 // If somehow we got a dummy null intent in the middle,
11017 // then skip it. DO NOT skip a null intent when it is
11018 // the only one in the list -- this is to support the
11019 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011020 continue;
11021 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011022 si.deliveredTime = SystemClock.uptimeMillis();
11023 r.deliveredStarts.add(si);
11024 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011025 if (si.neededGrants != null) {
11026 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11027 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011028 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011029 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011030 if (!oomAdjusted) {
11031 oomAdjusted = true;
11032 updateOomAdjLocked(r.app);
11033 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011034 int flags = 0;
11035 if (si.deliveryCount > 0) {
11036 flags |= Service.START_FLAG_RETRY;
11037 }
11038 if (si.doneExecutingCount > 0) {
11039 flags |= Service.START_FLAG_REDELIVERY;
11040 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011041 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011042 } catch (RemoteException e) {
11043 // Remote process gone... we'll let the normal cleanup take
11044 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011045 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011046 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011048 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 break;
11050 }
11051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 }
11053
11054 private final boolean requestServiceBindingLocked(ServiceRecord r,
11055 IntentBindRecord i, boolean rebind) {
11056 if (r.app == null || r.app.thread == null) {
11057 // If service is not currently running, can't yet bind.
11058 return false;
11059 }
11060 if ((!i.requested || rebind) && i.apps.size() > 0) {
11061 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011062 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011063 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11064 if (!rebind) {
11065 i.requested = true;
11066 }
11067 i.hasBound = true;
11068 i.doRebind = false;
11069 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011070 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011071 return false;
11072 }
11073 }
11074 return true;
11075 }
11076
11077 private final void requestServiceBindingsLocked(ServiceRecord r) {
11078 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11079 while (bindings.hasNext()) {
11080 IntentBindRecord i = bindings.next();
11081 if (!requestServiceBindingLocked(r, i, false)) {
11082 break;
11083 }
11084 }
11085 }
11086
11087 private final void realStartServiceLocked(ServiceRecord r,
11088 ProcessRecord app) throws RemoteException {
11089 if (app.thread == null) {
11090 throw new RemoteException();
11091 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011092 if (DEBUG_MU)
11093 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011094 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011096 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011097
11098 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011099 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011100 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101
11102 boolean created = false;
11103 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011104 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011105 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011106 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011108 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011109 synchronized (r.stats.getBatteryStats()) {
11110 r.stats.startLaunchedLocked();
11111 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011112 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011113 app.thread.scheduleCreateService(r, r.serviceInfo,
11114 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011115 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 created = true;
11117 } finally {
11118 if (!created) {
11119 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011120 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 }
11122 }
11123
11124 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011125
11126 // If the service is in the started state, and there are no
11127 // pending arguments, then fake up one so its onStartCommand() will
11128 // be called.
11129 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011130 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011131 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011132 }
11133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011134 sendServiceArgsLocked(r, true);
11135 }
11136
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011137 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11138 boolean allowCancel) {
11139 boolean canceled = false;
11140
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011141 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011142 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011143 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011144
Dianne Hackborn070783f2010-12-29 16:46:28 -080011145 if ((r.serviceInfo.applicationInfo.flags
11146 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11147 minDuration /= 4;
11148 }
11149
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011150 // Any delivered but not yet finished starts should be put back
11151 // on the pending list.
11152 final int N = r.deliveredStarts.size();
11153 if (N > 0) {
11154 for (int i=N-1; i>=0; i--) {
11155 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011156 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011157 if (si.intent == null) {
11158 // We'll generate this again if needed.
11159 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11160 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11161 r.pendingStarts.add(0, si);
11162 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11163 dur *= 2;
11164 if (minDuration < dur) minDuration = dur;
11165 if (resetTime < dur) resetTime = dur;
11166 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011167 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011168 + r.name);
11169 canceled = true;
11170 }
11171 }
11172 r.deliveredStarts.clear();
11173 }
11174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175 r.totalRestartCount++;
11176 if (r.restartDelay == 0) {
11177 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011178 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011179 } else {
11180 // If it has been a "reasonably long time" since the service
11181 // was started, then reset our restart duration back to
11182 // the beginning, so we don't infinitely increase the duration
11183 // on a service that just occasionally gets killed (which is
11184 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011185 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011187 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011189 if ((r.serviceInfo.applicationInfo.flags
11190 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11191 // Services in peristent processes will restart much more
11192 // quickly, since they are pretty important. (Think SystemUI).
11193 r.restartDelay += minDuration/2;
11194 } else {
11195 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11196 if (r.restartDelay < minDuration) {
11197 r.restartDelay = minDuration;
11198 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011200 }
11201 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011202
11203 r.nextRestartTime = now + r.restartDelay;
11204
11205 // Make sure that we don't end up restarting a bunch of services
11206 // all at the same time.
11207 boolean repeat;
11208 do {
11209 repeat = false;
11210 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11211 ServiceRecord r2 = mRestartingServices.get(i);
11212 if (r2 != r && r.nextRestartTime
11213 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11214 && r.nextRestartTime
11215 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11216 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11217 r.restartDelay = r.nextRestartTime - now;
11218 repeat = true;
11219 break;
11220 }
11221 }
11222 } while (repeat);
11223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 if (!mRestartingServices.contains(r)) {
11225 mRestartingServices.add(r);
11226 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011227
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011228 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011231 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011233 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011234 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011235 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 r.shortName, r.restartDelay);
11237
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011238 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 }
11240
11241 final void performServiceRestartLocked(ServiceRecord r) {
11242 if (!mRestartingServices.contains(r)) {
11243 return;
11244 }
11245 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11246 }
11247
11248 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11249 if (r.restartDelay == 0) {
11250 return false;
11251 }
11252 r.resetRestartCounter();
11253 mRestartingServices.remove(r);
11254 mHandler.removeCallbacks(r.restarter);
11255 return true;
11256 }
11257
11258 private final boolean bringUpServiceLocked(ServiceRecord r,
11259 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011260 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 //r.dump(" ");
11262
Dianne Hackborn36124872009-10-08 16:22:03 -070011263 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 sendServiceArgsLocked(r, false);
11265 return true;
11266 }
11267
11268 if (!whileRestarting && r.restartDelay > 0) {
11269 // If waiting for a restart, then do nothing.
11270 return true;
11271 }
11272
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011273 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011275 // We are now bringing the service up, so no longer in the
11276 // restarting state.
11277 mRestartingServices.remove(r);
11278
Dianne Hackborne7f97212011-02-24 14:40:20 -080011279 // Service is now being launched, its package can't be stopped.
11280 try {
11281 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011282 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011283 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011284 } catch (IllegalArgumentException e) {
11285 Slog.w(TAG, "Failed trying to unstop package "
11286 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011287 }
11288
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011289 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011290 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011291 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011293 if (!isolated) {
11294 app = getProcessRecordLocked(appName, r.appInfo.uid);
11295 if (DEBUG_MU)
11296 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11297 if (app != null && app.thread != null) {
11298 try {
11299 app.addPackage(r.appInfo.packageName);
11300 realStartServiceLocked(r, app);
11301 return true;
11302 } catch (RemoteException e) {
11303 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11304 }
11305
11306 // If a dead object exception was thrown -- fall through to
11307 // restart the application.
11308 }
11309 } else {
11310 // If this service runs in an isolated process, then each time
11311 // we call startProcessLocked() we will get a new isolated
11312 // process, starting another process if we are currently waiting
11313 // for a previous process to come up. To deal with this, we store
11314 // in the service any current isolated process it is running in or
11315 // waiting to have come up.
11316 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 }
11318
Dianne Hackborn36124872009-10-08 16:22:03 -070011319 // Not running -- get it started, and enqueue this service record
11320 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011321 if (app == null) {
11322 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11323 "service", r.name, false, isolated)) == null) {
11324 Slog.w(TAG, "Unable to launch app "
11325 + r.appInfo.packageName + "/"
11326 + r.appInfo.uid + " for service "
11327 + r.intent.getIntent() + ": process is bad");
11328 bringDownServiceLocked(r, true);
11329 return false;
11330 }
11331 if (isolated) {
11332 r.isolatedProc = app;
11333 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011334 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011336 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011337 mPendingServices.add(r);
11338 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011340 return true;
11341 }
11342
11343 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011344 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345 //r.dump(" ");
11346
11347 // Does it still need to run?
11348 if (!force && r.startRequested) {
11349 return;
11350 }
11351 if (r.connections.size() > 0) {
11352 if (!force) {
11353 // XXX should probably keep a count of the number of auto-create
11354 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011355 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011357 ArrayList<ConnectionRecord> cr = it.next();
11358 for (int i=0; i<cr.size(); i++) {
11359 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11360 return;
11361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 }
11363 }
11364 }
11365
11366 // Report to all of the connections that the service is no longer
11367 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011368 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011370 ArrayList<ConnectionRecord> c = it.next();
11371 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011372 ConnectionRecord cr = c.get(i);
11373 // There is still a connection to the service that is
11374 // being brought down. Mark it as dead.
11375 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011376 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011377 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011378 } catch (Exception e) {
11379 Slog.w(TAG, "Failure disconnecting service " + r.name +
11380 " to connection " + c.get(i).conn.asBinder() +
11381 " (in " + c.get(i).binding.client.processName + ")", e);
11382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011383 }
11384 }
11385 }
11386
11387 // Tell the service that it has been unbound.
11388 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11389 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11390 while (it.hasNext()) {
11391 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011392 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 + ": hasBound=" + ibr.hasBound);
11394 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11395 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011396 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011397 updateOomAdjLocked(r.app);
11398 ibr.hasBound = false;
11399 r.app.thread.scheduleUnbindService(r,
11400 ibr.intent.getIntent());
11401 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011402 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011403 + r.shortName, e);
11404 serviceDoneExecutingLocked(r, true);
11405 }
11406 }
11407 }
11408 }
11409
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011410 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011411 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 System.identityHashCode(r), r.shortName,
11413 (r.app != null) ? r.app.pid : -1);
11414
Amith Yamasani742a6712011-05-04 14:49:28 -070011415 mServiceMap.removeServiceByName(r.name, r.userId);
11416 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011417 r.totalRestartCount = 0;
11418 unscheduleServiceRestartLocked(r);
11419
11420 // Also make sure it is not on the pending list.
11421 int N = mPendingServices.size();
11422 for (int i=0; i<N; i++) {
11423 if (mPendingServices.get(i) == r) {
11424 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011425 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 i--;
11427 N--;
11428 }
11429 }
11430
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011431 r.cancelNotification();
11432 r.isForeground = false;
11433 r.foregroundId = 0;
11434 r.foregroundNoti = null;
11435
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011436 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011437 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011438 r.pendingStarts.clear();
11439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011440 if (r.app != null) {
11441 synchronized (r.stats.getBatteryStats()) {
11442 r.stats.stopLaunchedLocked();
11443 }
11444 r.app.services.remove(r);
11445 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011446 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011447 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 mStoppingServices.add(r);
11449 updateOomAdjLocked(r.app);
11450 r.app.thread.scheduleStopService(r);
11451 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011452 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 + r.shortName, e);
11454 serviceDoneExecutingLocked(r, true);
11455 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011456 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011457 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011458 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011459 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011460 }
11461 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011462 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011463 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011465
11466 if (r.bindings.size() > 0) {
11467 r.bindings.clear();
11468 }
11469
11470 if (r.restarter instanceof ServiceRestarter) {
11471 ((ServiceRestarter)r.restarter).setService(null);
11472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 }
11474
11475 ComponentName startServiceLocked(IApplicationThread caller,
11476 Intent service, String resolvedType,
11477 int callingPid, int callingUid) {
11478 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011479 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 + " type=" + resolvedType + " args=" + service.getExtras());
11481
11482 if (caller != null) {
11483 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11484 if (callerApp == null) {
11485 throw new SecurityException(
11486 "Unable to find app for caller " + caller
11487 + " (pid=" + Binder.getCallingPid()
11488 + ") when starting service " + service);
11489 }
11490 }
11491
11492 ServiceLookupResult res =
11493 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011494 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011495 if (res == null) {
11496 return null;
11497 }
11498 if (res.record == null) {
11499 return new ComponentName("!", res.permission != null
11500 ? res.permission : "private to package");
11501 }
11502 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011503 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11504 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011506 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507 }
11508 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011509 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011510 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011511 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011512 r.lastActivity = SystemClock.uptimeMillis();
11513 synchronized (r.stats.getBatteryStats()) {
11514 r.stats.startRunningLocked();
11515 }
11516 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11517 return new ComponentName("!", "Service process is bad");
11518 }
11519 return r.name;
11520 }
11521 }
11522
11523 public ComponentName startService(IApplicationThread caller, Intent service,
11524 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011525 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 // Refuse possible leaked file descriptors
11527 if (service != null && service.hasFileDescriptors() == true) {
11528 throw new IllegalArgumentException("File descriptors passed in Intent");
11529 }
11530
Amith Yamasani742a6712011-05-04 14:49:28 -070011531 if (DEBUG_SERVICE)
11532 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533 synchronized(this) {
11534 final int callingPid = Binder.getCallingPid();
11535 final int callingUid = Binder.getCallingUid();
11536 final long origId = Binder.clearCallingIdentity();
11537 ComponentName res = startServiceLocked(caller, service,
11538 resolvedType, callingPid, callingUid);
11539 Binder.restoreCallingIdentity(origId);
11540 return res;
11541 }
11542 }
11543
11544 ComponentName startServiceInPackage(int uid,
11545 Intent service, String resolvedType) {
11546 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011547 if (DEBUG_SERVICE)
11548 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011549 final long origId = Binder.clearCallingIdentity();
11550 ComponentName res = startServiceLocked(null, service,
11551 resolvedType, -1, uid);
11552 Binder.restoreCallingIdentity(origId);
11553 return res;
11554 }
11555 }
11556
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011557 private void stopServiceLocked(ServiceRecord service) {
11558 synchronized (service.stats.getBatteryStats()) {
11559 service.stats.stopRunningLocked();
11560 }
11561 service.startRequested = false;
11562 service.callStart = false;
11563 bringDownServiceLocked(service, false);
11564 }
11565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 public int stopService(IApplicationThread caller, Intent service,
11567 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011568 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011569 // Refuse possible leaked file descriptors
11570 if (service != null && service.hasFileDescriptors() == true) {
11571 throw new IllegalArgumentException("File descriptors passed in Intent");
11572 }
11573
11574 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011575 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 + " type=" + resolvedType);
11577
11578 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11579 if (caller != null && callerApp == null) {
11580 throw new SecurityException(
11581 "Unable to find app for caller " + caller
11582 + " (pid=" + Binder.getCallingPid()
11583 + ") when stopping service " + service);
11584 }
11585
11586 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011587 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11588 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589 if (r != null) {
11590 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011592 try {
11593 stopServiceLocked(r.record);
11594 } finally {
11595 Binder.restoreCallingIdentity(origId);
11596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 return 1;
11598 }
11599 return -1;
11600 }
11601 }
11602
11603 return 0;
11604 }
11605
11606 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011607 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 // Refuse possible leaked file descriptors
11609 if (service != null && service.hasFileDescriptors() == true) {
11610 throw new IllegalArgumentException("File descriptors passed in Intent");
11611 }
11612
11613 IBinder ret = null;
11614
11615 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011616 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11617 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011618
11619 if (r != null) {
11620 // r.record is null if findServiceLocked() failed the caller permission check
11621 if (r.record == null) {
11622 throw new SecurityException(
11623 "Permission Denial: Accessing service " + r.record.name
11624 + " from pid=" + Binder.getCallingPid()
11625 + ", uid=" + Binder.getCallingUid()
11626 + " requires " + r.permission);
11627 }
11628 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11629 if (ib != null) {
11630 ret = ib.binder;
11631 }
11632 }
11633 }
11634
11635 return ret;
11636 }
11637
11638 public boolean stopServiceToken(ComponentName className, IBinder token,
11639 int startId) {
11640 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011641 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 + " " + token + " startId=" + startId);
11643 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011644 if (r != null) {
11645 if (startId >= 0) {
11646 // Asked to only stop if done with all work. Note that
11647 // to avoid leaks, we will take this as dropping all
11648 // start items up to and including this one.
11649 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11650 if (si != null) {
11651 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011652 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11653 cur.removeUriPermissionsLocked();
11654 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011655 break;
11656 }
11657 }
11658 }
11659
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011660 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011661 return false;
11662 }
11663
11664 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011665 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011666 + " is last, but have " + r.deliveredStarts.size()
11667 + " remaining args");
11668 }
11669 }
11670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011671 synchronized (r.stats.getBatteryStats()) {
11672 r.stats.stopRunningLocked();
11673 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011674 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 }
11676 final long origId = Binder.clearCallingIdentity();
11677 bringDownServiceLocked(r, false);
11678 Binder.restoreCallingIdentity(origId);
11679 return true;
11680 }
11681 }
11682 return false;
11683 }
11684
11685 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011686 int id, Notification notification, boolean removeNotification) {
11687 final long origId = Binder.clearCallingIdentity();
11688 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011689 synchronized(this) {
11690 ServiceRecord r = findServiceLocked(className, token);
11691 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011692 if (id != 0) {
11693 if (notification == null) {
11694 throw new IllegalArgumentException("null notification");
11695 }
11696 if (r.foregroundId != id) {
11697 r.cancelNotification();
11698 r.foregroundId = id;
11699 }
11700 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11701 r.foregroundNoti = notification;
11702 r.isForeground = true;
11703 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011704 if (r.app != null) {
11705 updateServiceForegroundLocked(r.app, true);
11706 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011707 } else {
11708 if (r.isForeground) {
11709 r.isForeground = false;
11710 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011711 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011712 updateServiceForegroundLocked(r.app, true);
11713 }
11714 }
11715 if (removeNotification) {
11716 r.cancelNotification();
11717 r.foregroundId = 0;
11718 r.foregroundNoti = null;
11719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011720 }
11721 }
11722 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011723 } finally {
11724 Binder.restoreCallingIdentity(origId);
11725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726 }
11727
11728 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11729 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011730 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 if (sr.isForeground) {
11732 anyForeground = true;
11733 break;
11734 }
11735 }
11736 if (anyForeground != proc.foregroundServices) {
11737 proc.foregroundServices = anyForeground;
11738 if (oomAdj) {
11739 updateOomAdjLocked();
11740 }
11741 }
11742 }
11743
11744 public int bindService(IApplicationThread caller, IBinder token,
11745 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011746 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011747 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011748 // Refuse possible leaked file descriptors
11749 if (service != null && service.hasFileDescriptors() == true) {
11750 throw new IllegalArgumentException("File descriptors passed in Intent");
11751 }
11752
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011753 checkValidCaller(Binder.getCallingUid(), userId);
11754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011755 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011756 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011757 + " type=" + resolvedType + " conn=" + connection.asBinder()
11758 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011759 if (DEBUG_MU)
11760 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11761 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11763 if (callerApp == null) {
11764 throw new SecurityException(
11765 "Unable to find app for caller " + caller
11766 + " (pid=" + Binder.getCallingPid()
11767 + ") when binding service " + service);
11768 }
11769
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011770 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011771 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011772 activity = mMainStack.isInStackLocked(token);
11773 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011774 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011775 return 0;
11776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777 }
11778
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011779 int clientLabel = 0;
11780 PendingIntent clientIntent = null;
11781
11782 if (callerApp.info.uid == Process.SYSTEM_UID) {
11783 // Hacky kind of thing -- allow system stuff to tell us
11784 // what they are, so we can report this elsewhere for
11785 // others to know why certain services are running.
11786 try {
11787 clientIntent = (PendingIntent)service.getParcelableExtra(
11788 Intent.EXTRA_CLIENT_INTENT);
11789 } catch (RuntimeException e) {
11790 }
11791 if (clientIntent != null) {
11792 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11793 if (clientLabel != 0) {
11794 // There are no useful extras in the intent, trash them.
11795 // System code calling with this stuff just needs to know
11796 // this will happen.
11797 service = service.cloneFilter();
11798 }
11799 }
11800 }
11801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011802 ServiceLookupResult res =
11803 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011804 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 if (res == null) {
11806 return 0;
11807 }
11808 if (res.record == null) {
11809 return -1;
11810 }
11811 ServiceRecord s = res.record;
11812
11813 final long origId = Binder.clearCallingIdentity();
11814
11815 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011816 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011817 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 }
11819
11820 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11821 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011822 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823
11824 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011825 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11826 if (clist == null) {
11827 clist = new ArrayList<ConnectionRecord>();
11828 s.connections.put(binder, clist);
11829 }
11830 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831 b.connections.add(c);
11832 if (activity != null) {
11833 if (activity.connections == null) {
11834 activity.connections = new HashSet<ConnectionRecord>();
11835 }
11836 activity.connections.add(c);
11837 }
11838 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011839 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11840 b.client.hasAboveClient = true;
11841 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011842 clist = mServiceConnections.get(binder);
11843 if (clist == null) {
11844 clist = new ArrayList<ConnectionRecord>();
11845 mServiceConnections.put(binder, clist);
11846 }
11847 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011848
11849 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11850 s.lastActivity = SystemClock.uptimeMillis();
11851 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11852 return 0;
11853 }
11854 }
11855
11856 if (s.app != null) {
11857 // This could have made the service more important.
11858 updateOomAdjLocked(s.app);
11859 }
11860
Joe Onorato8a9b2202010-02-26 18:56:32 -080011861 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 + ": received=" + b.intent.received
11863 + " apps=" + b.intent.apps.size()
11864 + " doRebind=" + b.intent.doRebind);
11865
11866 if (s.app != null && b.intent.received) {
11867 // Service is already running, so we can immediately
11868 // publish the connection.
11869 try {
11870 c.conn.connected(s.name, b.intent.binder);
11871 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011872 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011873 + " to connection " + c.conn.asBinder()
11874 + " (in " + c.binding.client.processName + ")", e);
11875 }
11876
11877 // If this is the first app connected back to this binding,
11878 // and the service had previously asked to be told when
11879 // rebound, then do so.
11880 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11881 requestServiceBindingLocked(s, b.intent, true);
11882 }
11883 } else if (!b.intent.requested) {
11884 requestServiceBindingLocked(s, b.intent, false);
11885 }
11886
11887 Binder.restoreCallingIdentity(origId);
11888 }
11889
11890 return 1;
11891 }
11892
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011893 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011894 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011895 IBinder binder = c.conn.asBinder();
11896 AppBindRecord b = c.binding;
11897 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011898 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11899 if (clist != null) {
11900 clist.remove(c);
11901 if (clist.size() == 0) {
11902 s.connections.remove(binder);
11903 }
11904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011905 b.connections.remove(c);
11906 if (c.activity != null && c.activity != skipAct) {
11907 if (c.activity.connections != null) {
11908 c.activity.connections.remove(c);
11909 }
11910 }
11911 if (b.client != skipApp) {
11912 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011913 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11914 b.client.updateHasAboveClientLocked();
11915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011916 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011917 clist = mServiceConnections.get(binder);
11918 if (clist != null) {
11919 clist.remove(c);
11920 if (clist.size() == 0) {
11921 mServiceConnections.remove(binder);
11922 }
11923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924
11925 if (b.connections.size() == 0) {
11926 b.intent.apps.remove(b.client);
11927 }
11928
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011929 if (!c.serviceDead) {
11930 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11931 + ": shouldUnbind=" + b.intent.hasBound);
11932 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11933 && b.intent.hasBound) {
11934 try {
11935 bumpServiceExecutingLocked(s, "unbind");
11936 updateOomAdjLocked(s.app);
11937 b.intent.hasBound = false;
11938 // Assume the client doesn't want to know about a rebind;
11939 // we will deal with that later if it asks for one.
11940 b.intent.doRebind = false;
11941 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11942 } catch (Exception e) {
11943 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11944 serviceDoneExecutingLocked(s, true);
11945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011946 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011947
11948 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11949 bringDownServiceLocked(s, false);
11950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951 }
11952 }
11953
11954 public boolean unbindService(IServiceConnection connection) {
11955 synchronized (this) {
11956 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011957 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011958 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11959 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011960 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 + connection.asBinder());
11962 return false;
11963 }
11964
11965 final long origId = Binder.clearCallingIdentity();
11966
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011967 while (clist.size() > 0) {
11968 ConnectionRecord r = clist.get(0);
11969 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011971 if (r.binding.service.app != null) {
11972 // This could have made the service less important.
11973 updateOomAdjLocked(r.binding.service.app);
11974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 }
11976
11977 Binder.restoreCallingIdentity(origId);
11978 }
11979
11980 return true;
11981 }
11982
11983 public void publishService(IBinder token, Intent intent, IBinder service) {
11984 // Refuse possible leaked file descriptors
11985 if (intent != null && intent.hasFileDescriptors() == true) {
11986 throw new IllegalArgumentException("File descriptors passed in Intent");
11987 }
11988
11989 synchronized(this) {
11990 if (!(token instanceof ServiceRecord)) {
11991 throw new IllegalArgumentException("Invalid service token");
11992 }
11993 ServiceRecord r = (ServiceRecord)token;
11994
11995 final long origId = Binder.clearCallingIdentity();
11996
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011997 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011998 + " " + intent + ": " + service);
11999 if (r != null) {
12000 Intent.FilterComparison filter
12001 = new Intent.FilterComparison(intent);
12002 IntentBindRecord b = r.bindings.get(filter);
12003 if (b != null && !b.received) {
12004 b.binder = service;
12005 b.requested = true;
12006 b.received = true;
12007 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012008 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 = r.connections.values().iterator();
12010 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012011 ArrayList<ConnectionRecord> clist = it.next();
12012 for (int i=0; i<clist.size(); i++) {
12013 ConnectionRecord c = clist.get(i);
12014 if (!filter.equals(c.binding.intent.intent)) {
12015 if (DEBUG_SERVICE) Slog.v(
12016 TAG, "Not publishing to: " + c);
12017 if (DEBUG_SERVICE) Slog.v(
12018 TAG, "Bound intent: " + c.binding.intent.intent);
12019 if (DEBUG_SERVICE) Slog.v(
12020 TAG, "Published intent: " + intent);
12021 continue;
12022 }
12023 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12024 try {
12025 c.conn.connected(r.name, service);
12026 } catch (Exception e) {
12027 Slog.w(TAG, "Failure sending service " + r.name +
12028 " to connection " + c.conn.asBinder() +
12029 " (in " + c.binding.client.processName + ")", e);
12030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012031 }
12032 }
12033 }
12034 }
12035
12036 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12037
12038 Binder.restoreCallingIdentity(origId);
12039 }
12040 }
12041 }
12042
12043 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12044 // Refuse possible leaked file descriptors
12045 if (intent != null && intent.hasFileDescriptors() == true) {
12046 throw new IllegalArgumentException("File descriptors passed in Intent");
12047 }
12048
12049 synchronized(this) {
12050 if (!(token instanceof ServiceRecord)) {
12051 throw new IllegalArgumentException("Invalid service token");
12052 }
12053 ServiceRecord r = (ServiceRecord)token;
12054
12055 final long origId = Binder.clearCallingIdentity();
12056
12057 if (r != null) {
12058 Intent.FilterComparison filter
12059 = new Intent.FilterComparison(intent);
12060 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012061 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012062 + " at " + b + ": apps="
12063 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012064
12065 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012066 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012067 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012068 // Applications have already bound since the last
12069 // unbind, so just rebind right here.
12070 requestServiceBindingLocked(r, b, true);
12071 } else {
12072 // Note to tell the service the next time there is
12073 // a new client.
12074 b.doRebind = true;
12075 }
12076 }
12077
Per Edelberg78f9fff2010-08-30 20:01:35 +020012078 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012079
12080 Binder.restoreCallingIdentity(origId);
12081 }
12082 }
12083 }
12084
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012085 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012086 synchronized(this) {
12087 if (!(token instanceof ServiceRecord)) {
12088 throw new IllegalArgumentException("Invalid service token");
12089 }
12090 ServiceRecord r = (ServiceRecord)token;
12091 boolean inStopping = mStoppingServices.contains(token);
12092 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012094 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 + " with incorrect token: given " + token
12096 + ", expected " + r);
12097 return;
12098 }
12099
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012100 if (type == 1) {
12101 // This is a call from a service start... take care of
12102 // book-keeping.
12103 r.callStart = true;
12104 switch (res) {
12105 case Service.START_STICKY_COMPATIBILITY:
12106 case Service.START_STICKY: {
12107 // We are done with the associated start arguments.
12108 r.findDeliveredStart(startId, true);
12109 // Don't stop if killed.
12110 r.stopIfKilled = false;
12111 break;
12112 }
12113 case Service.START_NOT_STICKY: {
12114 // We are done with the associated start arguments.
12115 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012116 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012117 // There is no more work, and this service
12118 // doesn't want to hang around if killed.
12119 r.stopIfKilled = true;
12120 }
12121 break;
12122 }
12123 case Service.START_REDELIVER_INTENT: {
12124 // We'll keep this item until they explicitly
12125 // call stop for it, but keep track of the fact
12126 // that it was delivered.
12127 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12128 if (si != null) {
12129 si.deliveryCount = 0;
12130 si.doneExecutingCount++;
12131 // Don't stop if killed.
12132 r.stopIfKilled = true;
12133 }
12134 break;
12135 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012136 case Service.START_TASK_REMOVED_COMPLETE: {
12137 // Special processing for onTaskRemoved(). Don't
12138 // impact normal onStartCommand() processing.
12139 r.findDeliveredStart(startId, true);
12140 break;
12141 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012142 default:
12143 throw new IllegalArgumentException(
12144 "Unknown service start result: " + res);
12145 }
12146 if (res == Service.START_STICKY_COMPATIBILITY) {
12147 r.callStart = false;
12148 }
12149 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012150 if (DEBUG_MU)
12151 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12152 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012153 final long origId = Binder.clearCallingIdentity();
12154 serviceDoneExecutingLocked(r, inStopping);
12155 Binder.restoreCallingIdentity(origId);
12156 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012157 Slog.w(TAG, "Done executing unknown service from pid "
12158 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159 }
12160 }
12161 }
12162
12163 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012164 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12165 + ": nesting=" + r.executeNesting
12166 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012167 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012168 r.executeNesting--;
12169 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012170 if (DEBUG_SERVICE) Slog.v(TAG,
12171 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012172 r.app.executingServices.remove(r);
12173 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012174 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12175 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012176 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12177 }
12178 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012179 if (DEBUG_SERVICE) Slog.v(TAG,
12180 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012181 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012182 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 }
12184 updateOomAdjLocked(r.app);
12185 }
12186 }
12187
12188 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012189 String anrMessage = null;
12190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 synchronized(this) {
12192 if (proc.executingServices.size() == 0 || proc.thread == null) {
12193 return;
12194 }
12195 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12196 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12197 ServiceRecord timeout = null;
12198 long nextTime = 0;
12199 while (it.hasNext()) {
12200 ServiceRecord sr = it.next();
12201 if (sr.executingStart < maxTime) {
12202 timeout = sr;
12203 break;
12204 }
12205 if (sr.executingStart > nextTime) {
12206 nextTime = sr.executingStart;
12207 }
12208 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012209 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012210 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012211 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012212 } else {
12213 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12214 msg.obj = proc;
12215 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12216 }
12217 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012218
12219 if (anrMessage != null) {
12220 appNotResponding(proc, null, null, anrMessage);
12221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222 }
12223
12224 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012225 // BACKUP AND RESTORE
12226 // =========================================================
12227
12228 // Cause the target app to be launched if necessary and its backup agent
12229 // instantiated. The backup agent will invoke backupAgentCreated() on the
12230 // activity manager to announce its creation.
12231 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012232 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012233 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12234
12235 synchronized(this) {
12236 // !!! TODO: currently no check here that we're already bound
12237 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12238 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12239 synchronized (stats) {
12240 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12241 }
12242
Dianne Hackborne7f97212011-02-24 14:40:20 -080012243 // Backup agent is now in use, its package can't be stopped.
12244 try {
12245 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012246 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012247 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012248 } catch (IllegalArgumentException e) {
12249 Slog.w(TAG, "Failed trying to unstop package "
12250 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012251 }
12252
Christopher Tate181fafa2009-05-14 11:12:14 -070012253 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012254 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12255 ? new ComponentName(app.packageName, app.backupAgentName)
12256 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012257 // startProcessLocked() returns existing proc's record if it's already running
12258 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012259 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012260 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012261 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012262 return false;
12263 }
12264
12265 r.app = proc;
12266 mBackupTarget = r;
12267 mBackupAppName = app.packageName;
12268
Christopher Tate6fa95972009-06-05 18:43:55 -070012269 // Try not to kill the process during backup
12270 updateOomAdjLocked(proc);
12271
Christopher Tate181fafa2009-05-14 11:12:14 -070012272 // If the process is already attached, schedule the creation of the backup agent now.
12273 // If it is not yet live, this will be done when it attaches to the framework.
12274 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012275 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012276 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012277 proc.thread.scheduleCreateBackupAgent(app,
12278 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012279 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012280 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012281 }
12282 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012283 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012284 }
12285 // Invariants: at this point, the target app process exists and the application
12286 // is either already running or in the process of coming up. mBackupTarget and
12287 // mBackupAppName describe the app, so that when it binds back to the AM we
12288 // know that it's scheduled for a backup-agent operation.
12289 }
12290
12291 return true;
12292 }
12293
12294 // A backup agent has just come up
12295 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012296 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012297 + " = " + agent);
12298
12299 synchronized(this) {
12300 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012301 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012302 return;
12303 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012304 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012305
Dianne Hackborn06740692010-09-22 22:46:21 -070012306 long oldIdent = Binder.clearCallingIdentity();
12307 try {
12308 IBackupManager bm = IBackupManager.Stub.asInterface(
12309 ServiceManager.getService(Context.BACKUP_SERVICE));
12310 bm.agentConnected(agentPackageName, agent);
12311 } catch (RemoteException e) {
12312 // can't happen; the backup manager service is local
12313 } catch (Exception e) {
12314 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12315 e.printStackTrace();
12316 } finally {
12317 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012318 }
12319 }
12320
12321 // done with this agent
12322 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012323 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012324 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012325 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012326 return;
12327 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012328
12329 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012330 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012331 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012332 return;
12333 }
12334
Christopher Tate181fafa2009-05-14 11:12:14 -070012335 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012336 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012337 return;
12338 }
12339
Christopher Tate6fa95972009-06-05 18:43:55 -070012340 ProcessRecord proc = mBackupTarget.app;
12341 mBackupTarget = null;
12342 mBackupAppName = null;
12343
12344 // Not backing this app up any more; reset its OOM adjustment
12345 updateOomAdjLocked(proc);
12346
Christopher Tatec7b31e32009-06-10 15:49:30 -070012347 // If the app crashed during backup, 'thread' will be null here
12348 if (proc.thread != null) {
12349 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012350 proc.thread.scheduleDestroyBackupAgent(appInfo,
12351 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012352 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012353 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012354 e.printStackTrace();
12355 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012356 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012357 }
12358 }
12359 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012360 // BROADCASTS
12361 // =========================================================
12362
Josh Bartel7f208742010-02-25 11:01:44 -060012363 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012364 List cur) {
12365 final ContentResolver resolver = mContext.getContentResolver();
12366 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12367 if (list == null) {
12368 return cur;
12369 }
12370 int N = list.size();
12371 for (int i=0; i<N; i++) {
12372 Intent intent = list.get(i);
12373 if (filter.match(resolver, intent, true, TAG) >= 0) {
12374 if (cur == null) {
12375 cur = new ArrayList<Intent>();
12376 }
12377 cur.add(intent);
12378 }
12379 }
12380 return cur;
12381 }
12382
Christopher Tatef46723b2012-01-26 14:19:24 -080012383 boolean isPendingBroadcastProcessLocked(int pid) {
12384 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12385 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387
Christopher Tatef46723b2012-01-26 14:19:24 -080012388 void skipPendingBroadcastLocked(int pid) {
12389 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12390 for (BroadcastQueue queue : mBroadcastQueues) {
12391 queue.skipPendingBroadcastLocked(pid);
12392 }
12393 }
12394
12395 // The app just attached; send any pending broadcasts that it should receive
12396 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12397 boolean didSomething = false;
12398 for (BroadcastQueue queue : mBroadcastQueues) {
12399 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012400 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012401 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012402 }
12403
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012404 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012405 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012406 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012407 synchronized(this) {
12408 ProcessRecord callerApp = null;
12409 if (caller != null) {
12410 callerApp = getRecordForAppLocked(caller);
12411 if (callerApp == null) {
12412 throw new SecurityException(
12413 "Unable to find app for caller " + caller
12414 + " (pid=" + Binder.getCallingPid()
12415 + ") when registering receiver " + receiver);
12416 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012417 if (callerApp.info.uid != Process.SYSTEM_UID &&
12418 !callerApp.pkgList.contains(callerPackage)) {
12419 throw new SecurityException("Given caller package " + callerPackage
12420 + " is not running in process " + callerApp);
12421 }
12422 } else {
12423 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012424 }
12425
12426 List allSticky = null;
12427
12428 // Look for any matching sticky broadcasts...
12429 Iterator actions = filter.actionsIterator();
12430 if (actions != null) {
12431 while (actions.hasNext()) {
12432 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012433 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434 }
12435 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012436 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 }
12438
12439 // The first sticky in the list is returned directly back to
12440 // the client.
12441 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12442
Joe Onorato8a9b2202010-02-26 18:56:32 -080012443 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012444 + ": " + sticky);
12445
12446 if (receiver == null) {
12447 return sticky;
12448 }
12449
12450 ReceiverList rl
12451 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12452 if (rl == null) {
12453 rl = new ReceiverList(this, callerApp,
12454 Binder.getCallingPid(),
12455 Binder.getCallingUid(), receiver);
12456 if (rl.app != null) {
12457 rl.app.receivers.add(rl);
12458 } else {
12459 try {
12460 receiver.asBinder().linkToDeath(rl, 0);
12461 } catch (RemoteException e) {
12462 return sticky;
12463 }
12464 rl.linkedToDeath = true;
12465 }
12466 mRegisteredReceivers.put(receiver.asBinder(), rl);
12467 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012468 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 rl.add(bf);
12470 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012471 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012472 }
12473 mReceiverResolver.addFilter(bf);
12474
12475 // Enqueue broadcasts for all existing stickies that match
12476 // this filter.
12477 if (allSticky != null) {
12478 ArrayList receivers = new ArrayList();
12479 receivers.add(bf);
12480
12481 int N = allSticky.size();
12482 for (int i=0; i<N; i++) {
12483 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012484 BroadcastQueue queue = broadcastQueueForIntent(intent);
12485 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012487 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012488 queue.enqueueParallelBroadcastLocked(r);
12489 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 }
12491 }
12492
12493 return sticky;
12494 }
12495 }
12496
12497 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012498 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499
Christopher Tatef46723b2012-01-26 14:19:24 -080012500 final long origId = Binder.clearCallingIdentity();
12501 try {
12502 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012503
Christopher Tatef46723b2012-01-26 14:19:24 -080012504 synchronized(this) {
12505 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012507 if (rl != null) {
12508 if (rl.curBroadcast != null) {
12509 BroadcastRecord r = rl.curBroadcast;
12510 final boolean doNext = finishReceiverLocked(
12511 receiver.asBinder(), r.resultCode, r.resultData,
12512 r.resultExtras, r.resultAbort, true);
12513 if (doNext) {
12514 doTrim = true;
12515 r.queue.processNextBroadcast(false);
12516 }
12517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518
Christopher Tatef46723b2012-01-26 14:19:24 -080012519 if (rl.app != null) {
12520 rl.app.receivers.remove(rl);
12521 }
12522 removeReceiverLocked(rl);
12523 if (rl.linkedToDeath) {
12524 rl.linkedToDeath = false;
12525 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012527 }
12528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529
Christopher Tatef46723b2012-01-26 14:19:24 -080012530 // If we actually concluded any broadcasts, we might now be able
12531 // to trim the recipients' apps from our working set
12532 if (doTrim) {
12533 trimApplications();
12534 return;
12535 }
12536
12537 } finally {
12538 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 }
12541
12542 void removeReceiverLocked(ReceiverList rl) {
12543 mRegisteredReceivers.remove(rl.receiver.asBinder());
12544 int N = rl.size();
12545 for (int i=0; i<N; i++) {
12546 mReceiverResolver.removeFilter(rl.get(i));
12547 }
12548 }
12549
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012550 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12551 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12552 ProcessRecord r = mLruProcesses.get(i);
12553 if (r.thread != null) {
12554 try {
12555 r.thread.dispatchPackageBroadcast(cmd, packages);
12556 } catch (RemoteException ex) {
12557 }
12558 }
12559 }
12560 }
12561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 private final int broadcastIntentLocked(ProcessRecord callerApp,
12563 String callerPackage, Intent intent, String resolvedType,
12564 IIntentReceiver resultTo, int resultCode, String resultData,
12565 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012566 boolean ordered, boolean sticky, int callingPid, int callingUid,
12567 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012568 intent = new Intent(intent);
12569
Dianne Hackborne7f97212011-02-24 14:40:20 -080012570 // By default broadcasts do not go to stopped apps.
12571 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12572
Joe Onorato8a9b2202010-02-26 18:56:32 -080012573 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012574 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012575 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012576 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012577 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012578 }
12579
12580 // Handle special intents: if this broadcast is from the package
12581 // manager about a package being removed, we need to remove all of
12582 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012583 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012584 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012585 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12586 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012587 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012588 || uidRemoved) {
12589 if (checkComponentPermission(
12590 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012591 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012592 == PackageManager.PERMISSION_GRANTED) {
12593 if (uidRemoved) {
12594 final Bundle intentExtras = intent.getExtras();
12595 final int uid = intentExtras != null
12596 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12597 if (uid >= 0) {
12598 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12599 synchronized (bs) {
12600 bs.removeUidStatsLocked(uid);
12601 }
12602 }
12603 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012604 // If resources are unvailble just force stop all
12605 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012606 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012607 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12608 if (list != null && (list.length > 0)) {
12609 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012610 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012611 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012612 sendPackageBroadcastLocked(
12613 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012614 }
12615 } else {
12616 Uri data = intent.getData();
12617 String ssp;
12618 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12619 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12620 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012621 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12622 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012623 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012624 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012625 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12626 new String[] {ssp});
12627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012628 }
12629 }
12630 }
12631 } else {
12632 String msg = "Permission Denial: " + intent.getAction()
12633 + " broadcast from " + callerPackage + " (pid=" + callingPid
12634 + ", uid=" + callingUid + ")"
12635 + " requires "
12636 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012637 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 throw new SecurityException(msg);
12639 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012640
12641 // Special case for adding a package: by default turn on compatibility
12642 // mode.
12643 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012644 Uri data = intent.getData();
12645 String ssp;
12646 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12647 mCompatModePackages.handlePackageAddedLocked(ssp,
12648 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012650 }
12651
12652 /*
12653 * If this is the time zone changed action, queue up a message that will reset the timezone
12654 * of all currently running processes. This message will get queued up before the broadcast
12655 * happens.
12656 */
12657 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12658 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12659 }
12660
Robert Greenwalt03595d02010-11-02 14:08:23 -070012661 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12662 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12663 }
12664
Robert Greenwalt434203a2010-10-11 16:00:27 -070012665 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12666 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12667 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12668 }
12669
Dianne Hackborn854060af2009-07-09 18:14:31 -070012670 /*
12671 * Prevent non-system code (defined here to be non-persistent
12672 * processes) from sending protected broadcasts.
12673 */
12674 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12675 || callingUid == Process.SHELL_UID || callingUid == 0) {
12676 // Always okay.
12677 } else if (callerApp == null || !callerApp.persistent) {
12678 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012679 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012680 intent.getAction())) {
12681 String msg = "Permission Denial: not allowed to send broadcast "
12682 + intent.getAction() + " from pid="
12683 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012684 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012685 throw new SecurityException(msg);
12686 }
12687 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012688 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012689 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012690 }
12691 }
12692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012693 // Add to the sticky list if requested.
12694 if (sticky) {
12695 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12696 callingPid, callingUid)
12697 != PackageManager.PERMISSION_GRANTED) {
12698 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12699 + callingPid + ", uid=" + callingUid
12700 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012701 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012702 throw new SecurityException(msg);
12703 }
12704 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012705 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012706 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012707 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708 }
12709 if (intent.getComponent() != null) {
12710 throw new SecurityException(
12711 "Sticky broadcasts can't target a specific component");
12712 }
12713 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12714 if (list == null) {
12715 list = new ArrayList<Intent>();
12716 mStickyBroadcasts.put(intent.getAction(), list);
12717 }
12718 int N = list.size();
12719 int i;
12720 for (i=0; i<N; i++) {
12721 if (intent.filterEquals(list.get(i))) {
12722 // This sticky already exists, replace it.
12723 list.set(i, new Intent(intent));
12724 break;
12725 }
12726 }
12727 if (i >= N) {
12728 list.add(new Intent(intent));
12729 }
12730 }
12731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 // Figure out who all will receive this broadcast.
12733 List receivers = null;
12734 List<BroadcastFilter> registeredReceivers = null;
12735 try {
12736 if (intent.getComponent() != null) {
12737 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012738 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012739 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012740 if (ai != null) {
12741 receivers = new ArrayList();
12742 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012743 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012744 receivers.add(ri);
12745 }
12746 } else {
12747 // Need to resolve the intent to interested receivers...
12748 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12749 == 0) {
12750 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012751 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012752 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012753 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012754 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12755 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012756 }
12757 } catch (RemoteException ex) {
12758 // pm is in same process, this will never happen.
12759 }
12760
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012761 final boolean replacePending =
12762 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12763
Joe Onorato8a9b2202010-02-26 18:56:32 -080012764 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012765 + " replacePending=" + replacePending);
12766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12768 if (!ordered && NR > 0) {
12769 // If we are not serializing this broadcast, then send the
12770 // registered receivers separately so they don't wait for the
12771 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012772 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12773 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012774 callerPackage, callingPid, callingUid, requiredPermission,
12775 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012776 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012777 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012778 TAG, "Enqueueing parallel broadcast " + r);
12779 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012780 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012781 queue.enqueueParallelBroadcastLocked(r);
12782 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 registeredReceivers = null;
12785 NR = 0;
12786 }
12787
12788 // Merge into one list.
12789 int ir = 0;
12790 if (receivers != null) {
12791 // A special case for PACKAGE_ADDED: do not allow the package
12792 // being added to see this broadcast. This prevents them from
12793 // using this as a back door to get run as soon as they are
12794 // installed. Maybe in the future we want to have a special install
12795 // broadcast or such for apps, but we'd like to deliberately make
12796 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012797 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012798 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12799 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12800 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012801 Uri data = intent.getData();
12802 if (data != null) {
12803 String pkgName = data.getSchemeSpecificPart();
12804 if (pkgName != null) {
12805 skipPackages = new String[] { pkgName };
12806 }
12807 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012808 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012809 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012810 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012811 if (skipPackages != null && (skipPackages.length > 0)) {
12812 for (String skipPackage : skipPackages) {
12813 if (skipPackage != null) {
12814 int NT = receivers.size();
12815 for (int it=0; it<NT; it++) {
12816 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12817 if (curt.activityInfo.packageName.equals(skipPackage)) {
12818 receivers.remove(it);
12819 it--;
12820 NT--;
12821 }
12822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 }
12824 }
12825 }
12826
12827 int NT = receivers != null ? receivers.size() : 0;
12828 int it = 0;
12829 ResolveInfo curt = null;
12830 BroadcastFilter curr = null;
12831 while (it < NT && ir < NR) {
12832 if (curt == null) {
12833 curt = (ResolveInfo)receivers.get(it);
12834 }
12835 if (curr == null) {
12836 curr = registeredReceivers.get(ir);
12837 }
12838 if (curr.getPriority() >= curt.priority) {
12839 // Insert this broadcast record into the final list.
12840 receivers.add(it, curr);
12841 ir++;
12842 curr = null;
12843 it++;
12844 NT++;
12845 } else {
12846 // Skip to the next ResolveInfo in the final list.
12847 it++;
12848 curt = null;
12849 }
12850 }
12851 }
12852 while (ir < NR) {
12853 if (receivers == null) {
12854 receivers = new ArrayList();
12855 }
12856 receivers.add(registeredReceivers.get(ir));
12857 ir++;
12858 }
12859
12860 if ((receivers != null && receivers.size() > 0)
12861 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012862 BroadcastQueue queue = broadcastQueueForIntent(intent);
12863 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012865 receivers, resultTo, resultCode, resultData, map, ordered,
12866 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012867 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012869 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012870 if (DEBUG_BROADCAST) {
12871 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012872 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012873 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012874 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012875 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012876 queue.enqueueOrderedBroadcastLocked(r);
12877 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012879 }
12880
Dianne Hackborna4972e92012-03-14 10:38:05 -070012881 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012882 }
12883
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012884 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 // Refuse possible leaked file descriptors
12886 if (intent != null && intent.hasFileDescriptors() == true) {
12887 throw new IllegalArgumentException("File descriptors passed in Intent");
12888 }
12889
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012890 int flags = intent.getFlags();
12891
12892 if (!mProcessesReady) {
12893 // if the caller really truly claims to know what they're doing, go
12894 // ahead and allow the broadcast without launching any receivers
12895 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12896 intent = new Intent(intent);
12897 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12898 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12899 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12900 + " before boot completion");
12901 throw new IllegalStateException("Cannot broadcast before boot completed");
12902 }
12903 }
12904
12905 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12906 throw new IllegalArgumentException(
12907 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12908 }
12909
12910 return intent;
12911 }
12912
12913 public final int broadcastIntent(IApplicationThread caller,
12914 Intent intent, String resolvedType, IIntentReceiver resultTo,
12915 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012916 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012917 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012918 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012919 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012921 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12922 final int callingPid = Binder.getCallingPid();
12923 final int callingUid = Binder.getCallingUid();
12924 final long origId = Binder.clearCallingIdentity();
12925 int res = broadcastIntentLocked(callerApp,
12926 callerApp != null ? callerApp.info.packageName : null,
12927 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012928 resultCode, resultData, map, requiredPermission, serialized, sticky,
12929 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012930 Binder.restoreCallingIdentity(origId);
12931 return res;
12932 }
12933 }
12934
12935 int broadcastIntentInPackage(String packageName, int uid,
12936 Intent intent, String resolvedType, IIntentReceiver resultTo,
12937 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012938 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012940 intent = verifyBroadcastLocked(intent);
12941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 final long origId = Binder.clearCallingIdentity();
12943 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12944 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012945 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012946 Binder.restoreCallingIdentity(origId);
12947 return res;
12948 }
12949 }
12950
Amith Yamasani742a6712011-05-04 14:49:28 -070012951 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12952 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 // Refuse possible leaked file descriptors
12954 if (intent != null && intent.hasFileDescriptors() == true) {
12955 throw new IllegalArgumentException("File descriptors passed in Intent");
12956 }
12957
12958 synchronized(this) {
12959 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12960 != PackageManager.PERMISSION_GRANTED) {
12961 String msg = "Permission Denial: unbroadcastIntent() from pid="
12962 + Binder.getCallingPid()
12963 + ", uid=" + Binder.getCallingUid()
12964 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012965 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012966 throw new SecurityException(msg);
12967 }
12968 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12969 if (list != null) {
12970 int N = list.size();
12971 int i;
12972 for (i=0; i<N; i++) {
12973 if (intent.filterEquals(list.get(i))) {
12974 list.remove(i);
12975 break;
12976 }
12977 }
12978 }
12979 }
12980 }
12981
12982 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12983 String resultData, Bundle resultExtras, boolean resultAbort,
12984 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012985 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12986 if (r == null) {
12987 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 return false;
12989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012990
Christopher Tatef46723b2012-01-26 14:19:24 -080012991 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12992 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993 }
12994
12995 public void finishReceiver(IBinder who, int resultCode, String resultData,
12996 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012997 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998
12999 // Refuse possible leaked file descriptors
13000 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13001 throw new IllegalArgumentException("File descriptors passed in Bundle");
13002 }
13003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013004 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013005 try {
13006 boolean doNext = false;
13007 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013008
Christopher Tatef46723b2012-01-26 14:19:24 -080013009 synchronized(this) {
13010 r = broadcastRecordForReceiverLocked(who);
13011 if (r != null) {
13012 doNext = r.queue.finishReceiverLocked(r, resultCode,
13013 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013015 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013016
Christopher Tatef46723b2012-01-26 14:19:24 -080013017 if (doNext) {
13018 r.queue.processNextBroadcast(false);
13019 }
13020 trimApplications();
13021 } finally {
13022 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 // =========================================================
13027 // INSTRUMENTATION
13028 // =========================================================
13029
13030 public boolean startInstrumentation(ComponentName className,
13031 String profileFile, int flags, Bundle arguments,
13032 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013033 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013034 // Refuse possible leaked file descriptors
13035 if (arguments != null && arguments.hasFileDescriptors()) {
13036 throw new IllegalArgumentException("File descriptors passed in Bundle");
13037 }
13038
13039 synchronized(this) {
13040 InstrumentationInfo ii = null;
13041 ApplicationInfo ai = null;
13042 try {
13043 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013044 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013046 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013047 } catch (PackageManager.NameNotFoundException e) {
13048 }
13049 if (ii == null) {
13050 reportStartInstrumentationFailure(watcher, className,
13051 "Unable to find instrumentation info for: " + className);
13052 return false;
13053 }
13054 if (ai == null) {
13055 reportStartInstrumentationFailure(watcher, className,
13056 "Unable to find instrumentation target package: " + ii.targetPackage);
13057 return false;
13058 }
13059
13060 int match = mContext.getPackageManager().checkSignatures(
13061 ii.targetPackage, ii.packageName);
13062 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13063 String msg = "Permission Denial: starting instrumentation "
13064 + className + " from pid="
13065 + Binder.getCallingPid()
13066 + ", uid=" + Binder.getCallingPid()
13067 + " not allowed because package " + ii.packageName
13068 + " does not have a signature matching the target "
13069 + ii.targetPackage;
13070 reportStartInstrumentationFailure(watcher, className, msg);
13071 throw new SecurityException(msg);
13072 }
13073
Amith Yamasani483f3b02012-03-13 16:08:00 -070013074 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013075 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013076 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013077 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013078 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013080 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013081 app.instrumentationProfileFile = profileFile;
13082 app.instrumentationArguments = arguments;
13083 app.instrumentationWatcher = watcher;
13084 app.instrumentationResultClass = className;
13085 Binder.restoreCallingIdentity(origId);
13086 }
13087
13088 return true;
13089 }
13090
13091 /**
13092 * Report errors that occur while attempting to start Instrumentation. Always writes the
13093 * error to the logs, but if somebody is watching, send the report there too. This enables
13094 * the "am" command to report errors with more information.
13095 *
13096 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13097 * @param cn The component name of the instrumentation.
13098 * @param report The error report.
13099 */
13100 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13101 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013102 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013103 try {
13104 if (watcher != null) {
13105 Bundle results = new Bundle();
13106 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13107 results.putString("Error", report);
13108 watcher.instrumentationStatus(cn, -1, results);
13109 }
13110 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013111 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013112 }
13113 }
13114
13115 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13116 if (app.instrumentationWatcher != null) {
13117 try {
13118 // NOTE: IInstrumentationWatcher *must* be oneway here
13119 app.instrumentationWatcher.instrumentationFinished(
13120 app.instrumentationClass,
13121 resultCode,
13122 results);
13123 } catch (RemoteException e) {
13124 }
13125 }
13126 app.instrumentationWatcher = null;
13127 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013128 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013129 app.instrumentationProfileFile = null;
13130 app.instrumentationArguments = null;
13131
Amith Yamasani483f3b02012-03-13 16:08:00 -070013132 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013133 }
13134
13135 public void finishInstrumentation(IApplicationThread target,
13136 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013137 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013138 // Refuse possible leaked file descriptors
13139 if (results != null && results.hasFileDescriptors()) {
13140 throw new IllegalArgumentException("File descriptors passed in Intent");
13141 }
13142
13143 synchronized(this) {
13144 ProcessRecord app = getRecordForAppLocked(target);
13145 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013146 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013147 return;
13148 }
13149 final long origId = Binder.clearCallingIdentity();
13150 finishInstrumentationLocked(app, resultCode, results);
13151 Binder.restoreCallingIdentity(origId);
13152 }
13153 }
13154
13155 // =========================================================
13156 // CONFIGURATION
13157 // =========================================================
13158
13159 public ConfigurationInfo getDeviceConfigurationInfo() {
13160 ConfigurationInfo config = new ConfigurationInfo();
13161 synchronized (this) {
13162 config.reqTouchScreen = mConfiguration.touchscreen;
13163 config.reqKeyboardType = mConfiguration.keyboard;
13164 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013165 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13166 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13168 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013169 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13170 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013171 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13172 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013173 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013174 }
13175 return config;
13176 }
13177
13178 public Configuration getConfiguration() {
13179 Configuration ci;
13180 synchronized(this) {
13181 ci = new Configuration(mConfiguration);
13182 }
13183 return ci;
13184 }
13185
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013186 public void updatePersistentConfiguration(Configuration values) {
13187 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13188 "updateConfiguration()");
13189 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13190 "updateConfiguration()");
13191 if (values == null) {
13192 throw new NullPointerException("Configuration must not be null");
13193 }
13194
13195 synchronized(this) {
13196 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013197 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013198 Binder.restoreCallingIdentity(origId);
13199 }
13200 }
13201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202 public void updateConfiguration(Configuration values) {
13203 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13204 "updateConfiguration()");
13205
13206 synchronized(this) {
13207 if (values == null && mWindowManager != null) {
13208 // sentinel: fetch the current configuration from the window manager
13209 values = mWindowManager.computeNewConfiguration();
13210 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013211
13212 if (mWindowManager != null) {
13213 mProcessList.applyDisplaySize(mWindowManager);
13214 }
13215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013216 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013217 if (values != null) {
13218 Settings.System.clearConfiguration(values);
13219 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013220 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013221 Binder.restoreCallingIdentity(origId);
13222 }
13223 }
13224
13225 /**
13226 * Do either or both things: (1) change the current configuration, and (2)
13227 * make sure the given activity is running with the (now) current
13228 * configuration. Returns true if the activity has been left running, or
13229 * false if <var>starting</var> is being destroyed to match the new
13230 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013231 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013232 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013233 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013234 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013235 // do nothing if we are headless
13236 if (mHeadless) return true;
13237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 int changes = 0;
13239
13240 boolean kept = true;
13241
13242 if (values != null) {
13243 Configuration newConfig = new Configuration(mConfiguration);
13244 changes = newConfig.updateFrom(values);
13245 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013246 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013247 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 }
13249
Doug Zongker2bec3d42009-12-04 12:52:44 -080013250 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251
Dianne Hackborn813075a62011-11-14 17:45:19 -080013252 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 saveLocaleLocked(values.locale,
13254 !values.locale.equals(mConfiguration.locale),
13255 values.userSetLocale);
13256 }
13257
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013258 mConfigurationSeq++;
13259 if (mConfigurationSeq <= 0) {
13260 mConfigurationSeq = 1;
13261 }
13262 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013263 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013264 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013265
13266 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013267
13268 // TODO: If our config changes, should we auto dismiss any currently
13269 // showing dialogs?
13270 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013271
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013272 AttributeCache ac = AttributeCache.instance();
13273 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013274 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013277 // Make sure all resources in our process are updated
13278 // right now, so that anyone who is going to retrieve
13279 // resource values after we return will be sure to get
13280 // the new ones. This is especially important during
13281 // boot, where the first config change needs to guarantee
13282 // all resources have that config before following boot
13283 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013284 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013285
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013286 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013287 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013288 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013289 mHandler.sendMessage(msg);
13290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013291
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013292 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13293 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 try {
13295 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013296 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013297 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013298 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013299 }
13300 } catch (Exception e) {
13301 }
13302 }
13303 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013304 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13305 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013307 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013308 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13309 broadcastIntentLocked(null, null,
13310 new Intent(Intent.ACTION_LOCALE_CHANGED),
13311 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013312 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013314 }
13315 }
13316
13317 if (changes != 0 && starting == null) {
13318 // If the configuration changed, and the caller is not already
13319 // in the process of starting an activity, then find the top
13320 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013321 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013322 }
13323
13324 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013325 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013326 // And we need to make sure at this point that all other activities
13327 // are made visible with the correct configuration.
13328 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 }
13330
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013331 if (values != null && mWindowManager != null) {
13332 mWindowManager.setNewConfiguration(mConfiguration);
13333 }
13334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013335 return kept;
13336 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013337
13338 /**
13339 * Decide based on the configuration whether we should shouw the ANR,
13340 * crash, etc dialogs. The idea is that if there is no affordnace to
13341 * press the on-screen buttons, we shouldn't show the dialog.
13342 *
13343 * A thought: SystemUI might also want to get told about this, the Power
13344 * dialog / global actions also might want different behaviors.
13345 */
13346 private static final boolean shouldShowDialogs(Configuration config) {
13347 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13348 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013350
13351 /**
13352 * Save the locale. You must be inside a synchronized (this) block.
13353 */
13354 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13355 if(isDiff) {
13356 SystemProperties.set("user.language", l.getLanguage());
13357 SystemProperties.set("user.region", l.getCountry());
13358 }
13359
13360 if(isPersist) {
13361 SystemProperties.set("persist.sys.language", l.getLanguage());
13362 SystemProperties.set("persist.sys.country", l.getCountry());
13363 SystemProperties.set("persist.sys.localevar", l.getVariant());
13364 }
13365 }
13366
Adam Powelldd8fab22012-03-22 17:47:27 -070013367 @Override
13368 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13369 ActivityRecord srec = ActivityRecord.forToken(token);
13370 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13371 }
13372
13373 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13374 Intent resultData) {
13375 ComponentName dest = destIntent.getComponent();
13376
13377 synchronized (this) {
13378 ActivityRecord srec = ActivityRecord.forToken(token);
13379 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13380 final int start = history.indexOf(srec);
13381 if (start < 0) {
13382 // Current activity is not in history stack; do nothing.
13383 return false;
13384 }
13385 int finishTo = start - 1;
13386 ActivityRecord parent = null;
13387 boolean foundParentInTask = false;
13388 if (dest != null) {
13389 TaskRecord tr = srec.task;
13390 for (int i = start - 1; i >= 0; i--) {
13391 ActivityRecord r = history.get(i);
13392 if (tr != r.task) {
13393 // Couldn't find parent in the same task; stop at the one above this.
13394 // (Root of current task; in-app "home" behavior)
13395 // Always at least finish the current activity.
13396 finishTo = Math.min(start - 1, i + 1);
13397 parent = history.get(finishTo);
13398 break;
13399 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13400 r.info.name.equals(dest.getClassName())) {
13401 finishTo = i;
13402 parent = r;
13403 foundParentInTask = true;
13404 break;
13405 }
13406 }
13407 }
13408
13409 if (mController != null) {
13410 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13411 if (next != null) {
13412 // ask watcher if this is allowed
13413 boolean resumeOK = true;
13414 try {
13415 resumeOK = mController.activityResuming(next.packageName);
13416 } catch (RemoteException e) {
13417 mController = null;
13418 }
13419
13420 if (!resumeOK) {
13421 return false;
13422 }
13423 }
13424 }
13425 final long origId = Binder.clearCallingIdentity();
13426 for (int i = start; i > finishTo; i--) {
13427 ActivityRecord r = history.get(i);
13428 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13429 "navigate-up");
13430 // Only return the supplied result for the first activity finished
13431 resultCode = Activity.RESULT_CANCELED;
13432 resultData = null;
13433 }
13434
13435 if (parent != null && foundParentInTask) {
13436 final int parentLaunchMode = parent.info.launchMode;
13437 final int destIntentFlags = destIntent.getFlags();
13438 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13439 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13440 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13441 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13442 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13443 } else {
13444 try {
13445 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13446 destIntent.getComponent(), 0, UserId.getCallingUserId());
13447 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13448 null, aInfo, parent.appToken, null,
13449 0, -1, parent.launchedFromUid, 0, null, true, null);
13450 foundParentInTask = res == ActivityManager.START_SUCCESS;
13451 } catch (RemoteException e) {
13452 foundParentInTask = false;
13453 }
13454 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13455 resultData, "navigate-up");
13456 }
13457 }
13458 Binder.restoreCallingIdentity(origId);
13459 return foundParentInTask;
13460 }
13461 }
13462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013463 // =========================================================
13464 // LIFETIME MANAGEMENT
13465 // =========================================================
13466
Christopher Tatef46723b2012-01-26 14:19:24 -080013467 // Returns which broadcast queue the app is the current [or imminent] receiver
13468 // on, or 'null' if the app is not an active broadcast recipient.
13469 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13470 BroadcastRecord r = app.curReceiver;
13471 if (r != null) {
13472 return r.queue;
13473 }
13474
13475 // It's not the current receiver, but it might be starting up to become one
13476 synchronized (this) {
13477 for (BroadcastQueue queue : mBroadcastQueues) {
13478 r = queue.mPendingBroadcast;
13479 if (r != null && r.curApp == app) {
13480 // found it; report which queue it's in
13481 return queue;
13482 }
13483 }
13484 }
13485
13486 return null;
13487 }
13488
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013489 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013490 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013491 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013492 // This adjustment has already been computed. If we are calling
13493 // from the top, we may have already computed our adjustment with
13494 // an earlier hidden adjustment that isn't really for us... if
13495 // so, use the new hidden adjustment.
13496 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013497 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013498 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013499 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013500 }
13501
13502 if (app.thread == null) {
13503 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013504 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013505 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013506 }
13507
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013508 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13509 app.adjSource = null;
13510 app.adjTarget = null;
13511 app.empty = false;
13512 app.hidden = false;
13513
13514 final int activitiesSize = app.activities.size();
13515
Dianne Hackborn7d608422011-08-07 16:24:18 -070013516 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013517 // The max adjustment doesn't allow this app to be anything
13518 // below foreground, so it is not worth doing work for it.
13519 app.adjType = "fixed";
13520 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013521 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013522 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013523 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013524 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013525 // System process can do UI, and when they do we want to have
13526 // them trim their memory after the user leaves the UI. To
13527 // facilitate this, here we need to determine whether or not it
13528 // is currently showing UI.
13529 app.systemNoUi = true;
13530 if (app == TOP_APP) {
13531 app.systemNoUi = false;
13532 } else if (activitiesSize > 0) {
13533 for (int j = 0; j < activitiesSize; j++) {
13534 final ActivityRecord r = app.activities.get(j);
13535 if (r.visible) {
13536 app.systemNoUi = false;
13537 break;
13538 }
13539 }
13540 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013541 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013542 }
13543
13544 final boolean hadForegroundActivities = app.foregroundActivities;
13545
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013546 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013547 app.keeping = false;
13548 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013549
The Android Open Source Project4df24232009-03-05 14:34:35 -080013550 // Determine the importance of the process, starting with most
13551 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013553 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013554 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013555 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013556 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013557 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013558 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013559 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013560 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013561 } else if (app.instrumentationClass != null) {
13562 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013563 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013564 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013565 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013566 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013567 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013568 // counts as being in the foreground for OOM killer purposes.
13569 // It's placed in a sched group based on the nature of the
13570 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013571 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013572 schedGroup = (queue == mFgBroadcastQueue)
13573 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013574 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013575 } else if (app.executingServices.size() > 0) {
13576 // An app that is currently executing a service callback also
13577 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013578 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013579 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013580 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013581 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013582 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013583 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013585 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013586 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013587 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013588 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013589 // A very not-needed process. If this is lower in the lru list,
13590 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013591 adj = hiddenAdj;
13592 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013593 app.hidden = true;
13594 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013595 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013596 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013597
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013598 boolean hasStoppingActivities = false;
13599
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013600 // Examine all activities if not already foreground.
13601 if (!app.foregroundActivities && activitiesSize > 0) {
13602 for (int j = 0; j < activitiesSize; j++) {
13603 final ActivityRecord r = app.activities.get(j);
13604 if (r.visible) {
13605 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013606 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13607 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013608 app.adjType = "visible";
13609 }
13610 schedGroup = Process.THREAD_GROUP_DEFAULT;
13611 app.hidden = false;
13612 app.foregroundActivities = true;
13613 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013614 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013615 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13616 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013617 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013618 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013619 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013620 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013621 } else if (r.state == ActivityState.STOPPING) {
13622 // We will apply the actual adjustment later, because
13623 // we want to allow this process to immediately go through
13624 // any memory trimming that is in effect.
13625 app.hidden = false;
13626 app.foregroundActivities = true;
13627 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013628 }
13629 }
13630 }
13631
Dianne Hackborn7d608422011-08-07 16:24:18 -070013632 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013633 if (app.foregroundServices) {
13634 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013635 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013636 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013637 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013638 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013639 } else if (app.forcingToForeground != null) {
13640 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013641 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013642 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013643 app.adjType = "force-foreground";
13644 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013645 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013646 }
13647 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013648
Dianne Hackborn7d608422011-08-07 16:24:18 -070013649 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013650 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013651 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013652 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013653 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013654 app.adjType = "heavy";
13655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013656
Dianne Hackborn7d608422011-08-07 16:24:18 -070013657 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013658 // This process is hosting what we currently consider to be the
13659 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013660 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013661 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013662 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013663 app.adjType = "home";
13664 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013665
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013666 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13667 && app.activities.size() > 0) {
13668 // This was the previous process that showed UI to the user.
13669 // We want to try to keep it around more aggressively, to give
13670 // a good experience around switching between two apps.
13671 adj = ProcessList.PREVIOUS_APP_ADJ;
13672 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13673 app.hidden = false;
13674 app.adjType = "previous";
13675 }
13676
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013677 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13678 + " reason=" + app.adjType);
13679
The Android Open Source Project4df24232009-03-05 14:34:35 -080013680 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013681 // there are applications dependent on our services or providers, but
13682 // this gives us a baseline and makes sure we don't get into an
13683 // infinite recursion.
13684 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013685 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013686
Christopher Tate6fa95972009-06-05 18:43:55 -070013687 if (mBackupTarget != null && app == mBackupTarget.app) {
13688 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013689 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013690 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013691 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013692 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013693 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013694 }
13695 }
13696
Dianne Hackborn7d608422011-08-07 16:24:18 -070013697 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013698 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013699 final long now = SystemClock.uptimeMillis();
13700 // This process is more important if the top activity is
13701 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013702 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013703 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013704 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013705 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013706 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013707 // If this process has shown some UI, let it immediately
13708 // go to the LRU list because it may be pretty heavy with
13709 // UI stuff. We'll tag it with a label just to help
13710 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013711 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013712 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013713 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013714 } else {
13715 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13716 // This service has seen some activity within
13717 // recent memory, so we will keep its process ahead
13718 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013719 if (adj > ProcessList.SERVICE_ADJ) {
13720 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013721 app.adjType = "started-services";
13722 app.hidden = false;
13723 }
13724 }
13725 // If we have let the service slide into the background
13726 // state, still have some text describing what it is doing
13727 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013728 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013729 app.adjType = "started-bg-services";
13730 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013731 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013732 // Don't kill this process because it is doing work; it
13733 // has said it is doing work.
13734 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013735 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013736 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013737 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013738 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013739 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013740 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013741 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013742 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013743 // XXX should compute this based on the max of
13744 // all connected clients.
13745 ConnectionRecord cr = clist.get(i);
13746 if (cr.binding.client == app) {
13747 // Binding to ourself is not interesting.
13748 continue;
13749 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013750 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013751 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013752 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013753 int myHiddenAdj = hiddenAdj;
13754 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013755 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013756 myHiddenAdj = client.hiddenAdj;
13757 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013758 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013759 }
13760 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013761 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013762 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013763 String adjType = null;
13764 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13765 // Not doing bind OOM management, so treat
13766 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013767 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013768 // If this process has shown some UI, let it immediately
13769 // go to the LRU list because it may be pretty heavy with
13770 // UI stuff. We'll tag it with a label just to help
13771 // debug and understand what is going on.
13772 if (adj > clientAdj) {
13773 adjType = "bound-bg-ui-services";
13774 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013775 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013776 clientAdj = adj;
13777 } else {
13778 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13779 // This service has not seen activity within
13780 // recent memory, so allow it to drop to the
13781 // LRU list if there is no other reason to keep
13782 // it around. We'll also tag it with a label just
13783 // to help debug and undertand what is going on.
13784 if (adj > clientAdj) {
13785 adjType = "bound-bg-services";
13786 }
13787 clientAdj = adj;
13788 }
13789 }
13790 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013791 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013792 // If this process has recently shown UI, and
13793 // the process that is binding to it is less
13794 // important than being visible, then we don't
13795 // care about the binding as much as we care
13796 // about letting this process get into the LRU
13797 // list to be killed and restarted if needed for
13798 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013799 if (app.hasShownUi && app != mHomeProcess
13800 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013801 adjType = "bound-bg-ui-services";
13802 } else {
13803 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13804 |Context.BIND_IMPORTANT)) != 0) {
13805 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013806 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13807 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13808 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13809 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13810 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013811 adj = clientAdj;
13812 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013813 app.pendingUiClean = true;
13814 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13815 adj = ProcessList.VISIBLE_APP_ADJ;
13816 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013817 }
13818 if (!client.hidden) {
13819 app.hidden = false;
13820 }
13821 if (client.keeping) {
13822 app.keeping = true;
13823 }
13824 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013825 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013826 }
13827 if (adjType != null) {
13828 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013829 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13830 .REASON_SERVICE_IN_USE;
13831 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013832 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013833 app.adjTarget = s.name;
13834 }
13835 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13836 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13837 schedGroup = Process.THREAD_GROUP_DEFAULT;
13838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013839 }
13840 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013841 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13842 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013843 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013844 (a.visible || a.state == ActivityState.RESUMED
13845 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013846 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013847 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13848 schedGroup = Process.THREAD_GROUP_DEFAULT;
13849 }
13850 app.hidden = false;
13851 app.adjType = "service";
13852 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13853 .REASON_SERVICE_IN_USE;
13854 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013855 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013856 app.adjTarget = s.name;
13857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013859 }
13860 }
13861 }
13862 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013863
Dianne Hackborn287952c2010-09-22 22:34:31 -070013864 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013865 // would like to avoid killing it unless it would prevent the current
13866 // application from running. By default we put the process in
13867 // with the rest of the background processes; as we scan through
13868 // its services we may bump it up from there.
13869 if (adj > hiddenAdj) {
13870 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013871 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013872 app.adjType = "bg-services";
13873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013874 }
13875
Dianne Hackborn7d608422011-08-07 16:24:18 -070013876 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013877 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013878 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013879 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013880 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013881 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013882 if (cpr.clients.size() != 0) {
13883 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013884 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013885 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013886 if (client == app) {
13887 // Being our own client is not interesting.
13888 continue;
13889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 int myHiddenAdj = hiddenAdj;
13891 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013892 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013893 myHiddenAdj = client.hiddenAdj;
13894 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013895 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013896 }
13897 }
13898 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013899 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013900 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013901 if (app.hasShownUi && app != mHomeProcess
13902 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013903 app.adjType = "bg-ui-provider";
13904 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013905 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13906 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013907 app.adjType = "provider";
13908 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013909 if (!client.hidden) {
13910 app.hidden = false;
13911 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013912 if (client.keeping) {
13913 app.keeping = true;
13914 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013915 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13916 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013917 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013918 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013919 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013920 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013921 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13922 schedGroup = Process.THREAD_GROUP_DEFAULT;
13923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013924 }
13925 }
13926 // If the provider has external (non-framework) process
13927 // dependencies, ensure that its adjustment is at least
13928 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013929 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013930 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13931 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013932 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013933 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013934 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013935 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013936 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 }
13938 }
13939 }
13940 }
13941
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013942 if (adj == ProcessList.SERVICE_ADJ) {
13943 if (doingAll) {
13944 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13945 mNewNumServiceProcs++;
13946 }
13947 if (app.serviceb) {
13948 adj = ProcessList.SERVICE_B_ADJ;
13949 }
13950 } else {
13951 app.serviceb = false;
13952 }
13953
13954 app.nonStoppingAdj = adj;
13955
13956 if (hasStoppingActivities) {
13957 // Only upgrade adjustment.
13958 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13959 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13960 app.adjType = "stopping";
13961 }
13962 }
13963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013964 app.curRawAdj = adj;
13965
Joe Onorato8a9b2202010-02-26 18:56:32 -080013966 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013967 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13968 if (adj > app.maxAdj) {
13969 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013970 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013971 schedGroup = Process.THREAD_GROUP_DEFAULT;
13972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013973 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013974 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013975 app.keeping = true;
13976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013977
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013978 if (app.hasAboveClient) {
13979 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13980 // then we need to drop its adjustment to be lower than the service's
13981 // in order to honor the request. We want to drop it by one adjustment
13982 // level... but there is special meaning applied to various levels so
13983 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013984 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013985 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013986 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13987 adj = ProcessList.VISIBLE_APP_ADJ;
13988 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13989 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13990 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13991 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013992 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013993 adj++;
13994 }
13995 }
13996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013997 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013998 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013999
14000 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014001 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14002 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014003 }
14004
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014005 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014006 }
14007
14008 /**
14009 * Ask a given process to GC right now.
14010 */
14011 final void performAppGcLocked(ProcessRecord app) {
14012 try {
14013 app.lastRequestedGc = SystemClock.uptimeMillis();
14014 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014015 if (app.reportLowMemory) {
14016 app.reportLowMemory = false;
14017 app.thread.scheduleLowMemory();
14018 } else {
14019 app.thread.processInBackground();
14020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014021 }
14022 } catch (Exception e) {
14023 // whatever.
14024 }
14025 }
14026
14027 /**
14028 * Returns true if things are idle enough to perform GCs.
14029 */
Josh Bartel7f208742010-02-25 11:01:44 -060014030 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014031 boolean processingBroadcasts = false;
14032 for (BroadcastQueue q : mBroadcastQueues) {
14033 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14034 processingBroadcasts = true;
14035 }
14036 }
14037 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014038 && (mSleeping || (mMainStack.mResumedActivity != null &&
14039 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014040 }
14041
14042 /**
14043 * Perform GCs on all processes that are waiting for it, but only
14044 * if things are idle.
14045 */
14046 final void performAppGcsLocked() {
14047 final int N = mProcessesToGc.size();
14048 if (N <= 0) {
14049 return;
14050 }
Josh Bartel7f208742010-02-25 11:01:44 -060014051 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014052 while (mProcessesToGc.size() > 0) {
14053 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014054 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014055 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14056 <= SystemClock.uptimeMillis()) {
14057 // To avoid spamming the system, we will GC processes one
14058 // at a time, waiting a few seconds between each.
14059 performAppGcLocked(proc);
14060 scheduleAppGcsLocked();
14061 return;
14062 } else {
14063 // It hasn't been long enough since we last GCed this
14064 // process... put it in the list to wait for its time.
14065 addProcessToGcListLocked(proc);
14066 break;
14067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014068 }
14069 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014070
14071 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014072 }
14073 }
14074
14075 /**
14076 * If all looks good, perform GCs on all processes waiting for them.
14077 */
14078 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014079 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014080 performAppGcsLocked();
14081 return;
14082 }
14083 // Still not idle, wait some more.
14084 scheduleAppGcsLocked();
14085 }
14086
14087 /**
14088 * Schedule the execution of all pending app GCs.
14089 */
14090 final void scheduleAppGcsLocked() {
14091 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014092
14093 if (mProcessesToGc.size() > 0) {
14094 // Schedule a GC for the time to the next process.
14095 ProcessRecord proc = mProcessesToGc.get(0);
14096 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14097
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014098 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014099 long now = SystemClock.uptimeMillis();
14100 if (when < (now+GC_TIMEOUT)) {
14101 when = now + GC_TIMEOUT;
14102 }
14103 mHandler.sendMessageAtTime(msg, when);
14104 }
14105 }
14106
14107 /**
14108 * Add a process to the array of processes waiting to be GCed. Keeps the
14109 * list in sorted order by the last GC time. The process can't already be
14110 * on the list.
14111 */
14112 final void addProcessToGcListLocked(ProcessRecord proc) {
14113 boolean added = false;
14114 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14115 if (mProcessesToGc.get(i).lastRequestedGc <
14116 proc.lastRequestedGc) {
14117 added = true;
14118 mProcessesToGc.add(i+1, proc);
14119 break;
14120 }
14121 }
14122 if (!added) {
14123 mProcessesToGc.add(0, proc);
14124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014125 }
14126
14127 /**
14128 * Set up to ask a process to GC itself. This will either do it
14129 * immediately, or put it on the list of processes to gc the next
14130 * time things are idle.
14131 */
14132 final void scheduleAppGcLocked(ProcessRecord app) {
14133 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014134 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014135 return;
14136 }
14137 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014138 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014139 scheduleAppGcsLocked();
14140 }
14141 }
14142
Dianne Hackborn287952c2010-09-22 22:34:31 -070014143 final void checkExcessivePowerUsageLocked(boolean doKills) {
14144 updateCpuStatsNow();
14145
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014146 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014147 boolean doWakeKills = doKills;
14148 boolean doCpuKills = doKills;
14149 if (mLastPowerCheckRealtime == 0) {
14150 doWakeKills = false;
14151 }
14152 if (mLastPowerCheckUptime == 0) {
14153 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014154 }
14155 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014156 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014157 }
14158 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014159 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14160 final long curUptime = SystemClock.uptimeMillis();
14161 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14162 mLastPowerCheckRealtime = curRealtime;
14163 mLastPowerCheckUptime = curUptime;
14164 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14165 doWakeKills = false;
14166 }
14167 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14168 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014169 }
14170 int i = mLruProcesses.size();
14171 while (i > 0) {
14172 i--;
14173 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014174 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014175 long wtime;
14176 synchronized (stats) {
14177 wtime = stats.getProcessWakeTime(app.info.uid,
14178 app.pid, curRealtime);
14179 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014180 long wtimeUsed = wtime - app.lastWakeTime;
14181 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14182 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014183 StringBuilder sb = new StringBuilder(128);
14184 sb.append("Wake for ");
14185 app.toShortString(sb);
14186 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014187 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014188 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014189 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014190 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014191 sb.append((wtimeUsed*100)/realtimeSince);
14192 sb.append("%)");
14193 Slog.i(TAG, sb.toString());
14194 sb.setLength(0);
14195 sb.append("CPU for ");
14196 app.toShortString(sb);
14197 sb.append(": over ");
14198 TimeUtils.formatDuration(uptimeSince, sb);
14199 sb.append(" used ");
14200 TimeUtils.formatDuration(cputimeUsed, sb);
14201 sb.append(" (");
14202 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014203 sb.append("%)");
14204 Slog.i(TAG, sb.toString());
14205 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014206 // If a process has held a wake lock for more
14207 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014208 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014209 if (doWakeKills && realtimeSince > 0
14210 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14211 synchronized (stats) {
14212 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14213 realtimeSince, wtimeUsed);
14214 }
14215 Slog.w(TAG, "Excessive wake lock in " + app.processName
14216 + " (pid " + app.pid + "): held " + wtimeUsed
14217 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014218 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14219 app.processName, app.setAdj, "excessive wake lock");
14220 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014221 } else if (doCpuKills && uptimeSince > 0
14222 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14223 synchronized (stats) {
14224 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14225 uptimeSince, cputimeUsed);
14226 }
14227 Slog.w(TAG, "Excessive CPU in " + app.processName
14228 + " (pid " + app.pid + "): used " + cputimeUsed
14229 + " during " + uptimeSince);
14230 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14231 app.processName, app.setAdj, "excessive cpu");
14232 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014233 } else {
14234 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014235 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014236 }
14237 }
14238 }
14239 }
14240
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014241 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014242 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014243 app.hiddenAdj = hiddenAdj;
14244
14245 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014246 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014247 }
14248
Dianne Hackborn287952c2010-09-22 22:34:31 -070014249 final boolean wasKeeping = app.keeping;
14250
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014251 boolean success = true;
14252
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014253 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014254
Jeff Brown10e89712011-07-08 18:52:57 -070014255 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014256 if (wasKeeping && !app.keeping) {
14257 // This app is no longer something we want to keep. Note
14258 // its current wake lock time to later know to kill it if
14259 // it is not behaving well.
14260 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14261 synchronized (stats) {
14262 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14263 app.pid, SystemClock.elapsedRealtime());
14264 }
14265 app.lastCpuTime = app.curCpuTime;
14266 }
14267
14268 app.setRawAdj = app.curRawAdj;
14269 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014270
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014271 if (app.curAdj != app.setAdj) {
14272 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014273 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014274 TAG, "Set " + app.pid + " " + app.processName +
14275 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014276 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014277 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014278 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014279 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014280 }
14281 }
14282 if (app.setSchedGroup != app.curSchedGroup) {
14283 app.setSchedGroup = app.curSchedGroup;
14284 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14285 "Setting process group of " + app.processName
14286 + " to " + app.curSchedGroup);
14287 if (app.waitingToKill != null &&
14288 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14289 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14290 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14291 app.processName, app.setAdj, app.waitingToKill);
14292 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014293 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014294 } else {
14295 if (true) {
14296 long oldId = Binder.clearCallingIdentity();
14297 try {
14298 Process.setProcessGroup(app.pid, app.curSchedGroup);
14299 } catch (Exception e) {
14300 Slog.w(TAG, "Failed setting process group of " + app.pid
14301 + " to " + app.curSchedGroup);
14302 e.printStackTrace();
14303 } finally {
14304 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014305 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014306 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014307 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014308 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014309 app.thread.setSchedulingGroup(app.curSchedGroup);
14310 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014311 }
14312 }
14313 }
14314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014315 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014316 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014317 }
14318
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014319 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014320 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014321 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014322 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014323 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014324 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014325 }
14326 }
14327 return resumedActivity;
14328 }
14329
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014330 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014331 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014332 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14333 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014334 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14335 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014336
14337 mAdjSeq++;
14338
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014339 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014340 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14341 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014342 if (nowHidden != wasHidden) {
14343 // Changed to/from hidden state, so apps after it in the LRU
14344 // list may also be changed.
14345 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014346 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014347 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014348 }
14349
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014350 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014351 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014352 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14353
14354 if (false) {
14355 RuntimeException e = new RuntimeException();
14356 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014357 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014358 }
14359
14360 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014361 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014362
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014363 // Let's determine how many processes we have running vs.
14364 // how many slots we have for background processes; we may want
14365 // to put multiple processes in a slot of there are enough of
14366 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014367 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014368 int factor = (mLruProcesses.size()-4)/numSlots;
14369 if (factor < 1) factor = 1;
14370 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014371 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014372 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014373
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014374 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014375 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014376 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014377 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014378 while (i > 0) {
14379 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014380 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014381 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014382 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14383 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014384 && app.curAdj == curHiddenAdj) {
14385 step++;
14386 if (step >= factor) {
14387 step = 0;
14388 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014390 }
14391 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014392 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014393 numHidden++;
14394 if (numHidden > mProcessLimit) {
14395 Slog.i(TAG, "No longer want " + app.processName
14396 + " (pid " + app.pid + "): hidden #" + numHidden);
14397 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14398 app.processName, app.setAdj, "too many background");
14399 app.killedBackground = true;
14400 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014401 }
14402 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014403 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14404 // If this is an isolated process, and there are no
14405 // services running in it, then the process is no longer
14406 // needed. We agressively kill these because we can by
14407 // definition not re-use the same process again, and it is
14408 // good to avoid having whatever code was running in them
14409 // left sitting around after no longer needed.
14410 Slog.i(TAG, "Isolated process " + app.processName
14411 + " (pid " + app.pid + ") no longer needed");
14412 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14413 app.processName, app.setAdj, "isolated not needed");
14414 app.killedBackground = true;
14415 Process.killProcessQuiet(app.pid);
14416 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014417 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14418 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14419 && !app.killedBackground) {
14420 numTrimming++;
14421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014422 }
14423 }
14424
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014425 mNumServiceProcs = mNewNumServiceProcs;
14426
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014427 // Now determine the memory trimming level of background processes.
14428 // Unfortunately we need to start at the back of the list to do this
14429 // properly. We only do this if the number of background apps we
14430 // are managing to keep around is less than half the maximum we desire;
14431 // if we are keeping a good number around, we'll let them use whatever
14432 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014433 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014434 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014435 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014436 int minFactor = 2;
14437 if (mHomeProcess != null) minFactor++;
14438 if (mPreviousProcess != null) minFactor++;
14439 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014440 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014441 int fgTrimLevel;
14442 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14443 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14444 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14445 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14446 } else {
14447 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14448 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014449 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014450 for (i=0; i<N; i++) {
14451 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014452 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14453 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014454 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014455 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14456 try {
14457 app.thread.scheduleTrimMemory(curLevel);
14458 } catch (RemoteException e) {
14459 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014460 if (false) {
14461 // For now we won't do this; our memory trimming seems
14462 // to be good enough at this point that destroying
14463 // activities causes more harm than good.
14464 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14465 && app != mHomeProcess && app != mPreviousProcess) {
14466 // For these apps we will also finish their activities
14467 // to help them free memory.
14468 mMainStack.destroyActivitiesLocked(app, false, "trim");
14469 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014470 }
14471 }
14472 app.trimMemoryLevel = curLevel;
14473 step++;
14474 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014475 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014476 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014477 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14478 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014479 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014480 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14481 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014482 break;
14483 }
14484 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014485 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014486 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014487 && app.thread != null) {
14488 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014489 app.thread.scheduleTrimMemory(
14490 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014491 } catch (RemoteException e) {
14492 }
14493 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014494 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014495 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014496 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014497 && app.pendingUiClean) {
14498 // If this application is now in the background and it
14499 // had done UI, then give it the special trim level to
14500 // have it free UI resources.
14501 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14502 if (app.trimMemoryLevel < level && app.thread != null) {
14503 try {
14504 app.thread.scheduleTrimMemory(level);
14505 } catch (RemoteException e) {
14506 }
14507 }
14508 app.pendingUiClean = false;
14509 }
14510 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014511 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014512 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014513 } catch (RemoteException e) {
14514 }
14515 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014516 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014517 }
14518 }
14519 } else {
14520 final int N = mLruProcesses.size();
14521 for (i=0; i<N; i++) {
14522 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014523 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014524 && app.pendingUiClean) {
14525 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14526 && app.thread != null) {
14527 try {
14528 app.thread.scheduleTrimMemory(
14529 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14530 } catch (RemoteException e) {
14531 }
14532 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014533 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014534 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014535 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014536 }
14537 }
14538
14539 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014540 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014542 }
14543
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014544 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014545 synchronized (this) {
14546 int i;
14547
14548 // First remove any unused application processes whose package
14549 // has been removed.
14550 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14551 final ProcessRecord app = mRemovedProcesses.get(i);
14552 if (app.activities.size() == 0
14553 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014554 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014555 TAG, "Exiting empty application process "
14556 + app.processName + " ("
14557 + (app.thread != null ? app.thread.asBinder() : null)
14558 + ")\n");
14559 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014560 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14561 app.processName, app.setAdj, "empty");
14562 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014563 } else {
14564 try {
14565 app.thread.scheduleExit();
14566 } catch (Exception e) {
14567 // Ignore exceptions.
14568 }
14569 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014570 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014571 mRemovedProcesses.remove(i);
14572
14573 if (app.persistent) {
14574 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014575 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014576 }
14577 }
14578 }
14579 }
14580
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014581 // Now update the oom adj for all processes.
14582 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014583 }
14584 }
14585
14586 /** This method sends the specified signal to each of the persistent apps */
14587 public void signalPersistentProcesses(int sig) throws RemoteException {
14588 if (sig != Process.SIGNAL_USR1) {
14589 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14590 }
14591
14592 synchronized (this) {
14593 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14594 != PackageManager.PERMISSION_GRANTED) {
14595 throw new SecurityException("Requires permission "
14596 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14597 }
14598
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014599 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14600 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014601 if (r.thread != null && r.persistent) {
14602 Process.sendSignal(r.pid, sig);
14603 }
14604 }
14605 }
14606 }
14607
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014608 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14609 if (proc == null || proc == mProfileProc) {
14610 proc = mProfileProc;
14611 path = mProfileFile;
14612 profileType = mProfileType;
14613 clearProfilerLocked();
14614 }
14615 if (proc == null) {
14616 return;
14617 }
14618 try {
14619 proc.thread.profilerControl(false, path, null, profileType);
14620 } catch (RemoteException e) {
14621 throw new IllegalStateException("Process disappeared");
14622 }
14623 }
14624
14625 private void clearProfilerLocked() {
14626 if (mProfileFd != null) {
14627 try {
14628 mProfileFd.close();
14629 } catch (IOException e) {
14630 }
14631 }
14632 mProfileApp = null;
14633 mProfileProc = null;
14634 mProfileFile = null;
14635 mProfileType = 0;
14636 mAutoStopProfiler = false;
14637 }
14638
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014639 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014640 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014641
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014642 try {
14643 synchronized (this) {
14644 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14645 // its own permission.
14646 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14647 != PackageManager.PERMISSION_GRANTED) {
14648 throw new SecurityException("Requires permission "
14649 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014650 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014651
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014652 if (start && fd == null) {
14653 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014654 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014655
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014656 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014657 if (process != null) {
14658 try {
14659 int pid = Integer.parseInt(process);
14660 synchronized (mPidsSelfLocked) {
14661 proc = mPidsSelfLocked.get(pid);
14662 }
14663 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014664 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014665
14666 if (proc == null) {
14667 HashMap<String, SparseArray<ProcessRecord>> all
14668 = mProcessNames.getMap();
14669 SparseArray<ProcessRecord> procs = all.get(process);
14670 if (procs != null && procs.size() > 0) {
14671 proc = procs.valueAt(0);
14672 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014673 }
14674 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014675
14676 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014677 throw new IllegalArgumentException("Unknown process: " + process);
14678 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014679
14680 if (start) {
14681 stopProfilerLocked(null, null, 0);
14682 setProfileApp(proc.info, proc.processName, path, fd, false);
14683 mProfileProc = proc;
14684 mProfileType = profileType;
14685 try {
14686 fd = fd.dup();
14687 } catch (IOException e) {
14688 fd = null;
14689 }
14690 proc.thread.profilerControl(start, path, fd, profileType);
14691 fd = null;
14692 mProfileFd = null;
14693 } else {
14694 stopProfilerLocked(proc, path, profileType);
14695 if (fd != null) {
14696 try {
14697 fd.close();
14698 } catch (IOException e) {
14699 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014700 }
14701 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014702
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014703 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014704 }
14705 } catch (RemoteException e) {
14706 throw new IllegalStateException("Process disappeared");
14707 } finally {
14708 if (fd != null) {
14709 try {
14710 fd.close();
14711 } catch (IOException e) {
14712 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014713 }
14714 }
14715 }
Andy McFadden824c5102010-07-09 16:26:57 -070014716
14717 public boolean dumpHeap(String process, boolean managed,
14718 String path, ParcelFileDescriptor fd) throws RemoteException {
14719
14720 try {
14721 synchronized (this) {
14722 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14723 // its own permission (same as profileControl).
14724 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14725 != PackageManager.PERMISSION_GRANTED) {
14726 throw new SecurityException("Requires permission "
14727 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14728 }
14729
14730 if (fd == null) {
14731 throw new IllegalArgumentException("null fd");
14732 }
14733
14734 ProcessRecord proc = null;
14735 try {
14736 int pid = Integer.parseInt(process);
14737 synchronized (mPidsSelfLocked) {
14738 proc = mPidsSelfLocked.get(pid);
14739 }
14740 } catch (NumberFormatException e) {
14741 }
14742
14743 if (proc == null) {
14744 HashMap<String, SparseArray<ProcessRecord>> all
14745 = mProcessNames.getMap();
14746 SparseArray<ProcessRecord> procs = all.get(process);
14747 if (procs != null && procs.size() > 0) {
14748 proc = procs.valueAt(0);
14749 }
14750 }
14751
14752 if (proc == null || proc.thread == null) {
14753 throw new IllegalArgumentException("Unknown process: " + process);
14754 }
14755
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014756 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14757 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014758 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14759 throw new SecurityException("Process not debuggable: " + proc);
14760 }
14761 }
14762
14763 proc.thread.dumpHeap(managed, path, fd);
14764 fd = null;
14765 return true;
14766 }
14767 } catch (RemoteException e) {
14768 throw new IllegalStateException("Process disappeared");
14769 } finally {
14770 if (fd != null) {
14771 try {
14772 fd.close();
14773 } catch (IOException e) {
14774 }
14775 }
14776 }
14777 }
14778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014779 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14780 public void monitor() {
14781 synchronized (this) { }
14782 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014783
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014784 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014785 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14786 ProcessRecord processRecord = mLruProcesses.get(i);
14787 try {
14788 if (processRecord.thread != null) {
14789 processRecord.thread.setCoreSettings(settings);
14790 }
14791 } catch (RemoteException re) {
14792 /* ignore */
14793 }
14794 }
14795 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014796
14797 // Multi-user methods
14798
Amith Yamasani742a6712011-05-04 14:49:28 -070014799 private int mCurrentUserId;
14800 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14801
14802 public boolean switchUser(int userId) {
14803 final int callingUid = Binder.getCallingUid();
14804 if (callingUid != 0 && callingUid != Process.myUid()) {
14805 Slog.e(TAG, "Trying to switch user from unauthorized app");
14806 return false;
14807 }
14808 if (mCurrentUserId == userId)
14809 return true;
14810
14811 synchronized (this) {
14812 // Check if user is already logged in, otherwise check if user exists first before
14813 // adding to the list of logged in users.
14814 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14815 if (!userExists(userId)) {
14816 return false;
14817 }
14818 mLoggedInUsers.append(userId, userId);
14819 }
14820
14821 mCurrentUserId = userId;
14822 boolean haveActivities = mMainStack.switchUser(userId);
14823 if (!haveActivities) {
14824 startHomeActivityLocked(userId);
14825 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014826
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014827 }
Amith Yamasani13593602012-03-22 16:16:17 -070014828
14829 // Inform of user switch
14830 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14831 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14832 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14833
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014834 return true;
14835 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014836
Amith Yamasani52f1d752012-03-28 18:19:29 -070014837 @Override
14838 public UserInfo getCurrentUser() throws RemoteException {
14839 final int callingUid = Binder.getCallingUid();
14840 if (callingUid != 0 && callingUid != Process.myUid()) {
14841 Slog.e(TAG, "Trying to get user from unauthorized app");
14842 return null;
14843 }
14844 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14845 }
14846
Amith Yamasani13593602012-03-22 16:16:17 -070014847 private void onUserRemoved(Intent intent) {
14848 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14849 if (extraUserId < 1) return;
14850
14851 // Kill all the processes for the user
14852 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14853 synchronized (this) {
14854 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14855 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14856 SparseArray<ProcessRecord> uids = uidMap.getValue();
14857 for (int i = 0; i < uids.size(); i++) {
14858 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14859 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14860 }
14861 }
14862 }
14863
14864 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14865 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14866 false, false, true, true, extraUserId);
14867 }
14868 }
14869 }
14870
Amith Yamasani742a6712011-05-04 14:49:28 -070014871 private boolean userExists(int userId) {
14872 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014873 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14874 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014875 } catch (RemoteException re) {
14876 // Won't happen, in same process
14877 }
14878
14879 return false;
14880 }
14881
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014882 private void checkValidCaller(int uid, int userId) {
14883 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14884
14885 throw new SecurityException("Caller uid=" + uid
14886 + " is not privileged to communicate with user=" + userId);
14887 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014888
14889 private int applyUserId(int uid, int userId) {
14890 return UserId.getUid(userId, uid);
14891 }
14892
14893 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014894 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014895 ApplicationInfo newInfo = new ApplicationInfo(info);
14896 newInfo.uid = applyUserId(info.uid, userId);
14897 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14898 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14899 + info.packageName;
14900 }
14901 return newInfo;
14902 }
14903
14904 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014905 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014906 || userId < 1) {
14907 return aInfo;
14908 }
14909
14910 ActivityInfo info = new ActivityInfo(aInfo);
14911 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14912 return info;
14913 }
14914
14915 static class ServiceMap {
14916
14917 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14918 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14919 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14920 mServicesByIntentPerUser = new SparseArray<
14921 HashMap<Intent.FilterComparison, ServiceRecord>>();
14922
14923 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14924 // TODO: Deal with global services
14925 if (DEBUG_MU)
14926 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14927 return getServices(callingUser).get(name);
14928 }
14929
14930 ServiceRecord getServiceByName(ComponentName name) {
14931 return getServiceByName(name, -1);
14932 }
14933
14934 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14935 // TODO: Deal with global services
14936 if (DEBUG_MU)
14937 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14938 return getServicesByIntent(callingUser).get(filter);
14939 }
14940
14941 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14942 return getServiceByIntent(filter, -1);
14943 }
14944
14945 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14946 // TODO: Deal with global services
14947 getServices(callingUser).put(name, value);
14948 }
14949
14950 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14951 ServiceRecord value) {
14952 // TODO: Deal with global services
14953 getServicesByIntent(callingUser).put(filter, value);
14954 }
14955
14956 void removeServiceByName(ComponentName name, int callingUser) {
14957 // TODO: Deal with global services
14958 ServiceRecord removed = getServices(callingUser).remove(name);
14959 if (DEBUG_MU)
14960 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14961 + " removed=" + removed);
14962 }
14963
14964 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14965 // TODO: Deal with global services
14966 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14967 if (DEBUG_MU)
14968 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14969 + " removed=" + removed);
14970 }
14971
14972 Collection<ServiceRecord> getAllServices(int callingUser) {
14973 // TODO: Deal with global services
14974 return getServices(callingUser).values();
14975 }
14976
14977 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14978 HashMap map = mServicesByNamePerUser.get(callingUser);
14979 if (map == null) {
14980 map = new HashMap<ComponentName, ServiceRecord>();
14981 mServicesByNamePerUser.put(callingUser, map);
14982 }
14983 return map;
14984 }
14985
14986 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14987 int callingUser) {
14988 HashMap map = mServicesByIntentPerUser.get(callingUser);
14989 if (map == null) {
14990 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14991 mServicesByIntentPerUser.put(callingUser, map);
14992 }
14993 return map;
14994 }
14995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014996}