blob: 8f69d2ff0698976601bfda1748d9934b9987410f [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 Yamasania4a54e22012-04-16 15:44:19 -07001811 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001812 // The system gets to run in any process. If there are multiple
1813 // processes with the same uid, just pick the first (this
1814 // should never happen).
1815 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1816 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001817 if (procs == null) return null;
1818 final int N = procs.size();
1819 for (int i = 0; i < N; i++) {
1820 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 ProcessRecord proc = mProcessNames.get(processName, uid);
1824 return proc;
1825 }
1826
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001828 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001829 try {
1830 if (pm.performDexOpt(packageName)) {
1831 mDidDexOpt = true;
1832 }
1833 } catch (RemoteException e) {
1834 }
1835 }
1836
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001837 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 int transit = mWindowManager.getPendingAppTransition();
1839 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1840 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1841 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1842 }
1843
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001844 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001846 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1847 boolean isolated) {
1848 ProcessRecord app;
1849 if (!isolated) {
1850 app = getProcessRecordLocked(processName, info.uid);
1851 } else {
1852 // If this is an isolated process, it can't re-use an existing process.
1853 app = null;
1854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 // We don't have to do anything more if:
1856 // (1) There is an existing application record; and
1857 // (2) The caller doesn't think it is dead, OR there is no thread
1858 // object attached to it so we know it couldn't have crashed; and
1859 // (3) There is a pid assigned to it, so it is either starting or
1860 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001861 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 + " app=" + app + " knownToBeDead=" + knownToBeDead
1863 + " thread=" + (app != null ? app.thread : null)
1864 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001865 if (app != null && app.pid > 0) {
1866 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001867 // We already have the app running, or are waiting for it to
1868 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001869 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001870 // If this is a new package in the process, add the package to the list
1871 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001872 return app;
1873 } else {
1874 // An application record is attached to a previous process,
1875 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001876 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001877 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 String hostingNameStr = hostingName != null
1882 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001883
1884 if (!isolated) {
1885 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1886 // If we are in the background, then check to see if this process
1887 // is bad. If so, we will just silently fail.
1888 if (mBadProcesses.get(info.processName, info.uid) != null) {
1889 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1890 + "/" + info.processName);
1891 return null;
1892 }
1893 } else {
1894 // When the user is explicitly starting a process, then clear its
1895 // crash count so that we won't make it bad until they see at
1896 // least one crash dialog again, and make the process good again
1897 // if it had been bad.
1898 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001899 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001900 mProcessCrashTimes.remove(info.processName, info.uid);
1901 if (mBadProcesses.get(info.processName, info.uid) != null) {
1902 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1903 info.processName);
1904 mBadProcesses.remove(info.processName, info.uid);
1905 if (app != null) {
1906 app.bad = false;
1907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
1909 }
1910 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001913 app = newProcessRecordLocked(null, info, processName, isolated);
1914 if (app == null) {
1915 Slog.w(TAG, "Failed making new process record for "
1916 + processName + "/" + info.uid + " isolated=" + isolated);
1917 return null;
1918 }
1919 mProcessNames.put(processName, app.uid, app);
1920 if (isolated) {
1921 mIsolatedProcesses.put(app.uid, app);
1922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 } else {
1924 // If this is a new package in the process, add the package to the list
1925 app.addPackage(info.packageName);
1926 }
1927
1928 // If the system is not ready yet, then hold off on starting this
1929 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001930 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001931 && !isAllowedWhileBooting(info)
1932 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 if (!mProcessesOnHold.contains(app)) {
1934 mProcessesOnHold.add(app);
1935 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001936 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 return app;
1938 }
1939
1940 startProcessLocked(app, hostingType, hostingNameStr);
1941 return (app.pid != 0) ? app : null;
1942 }
1943
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001944 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1945 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1946 }
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 private final void startProcessLocked(ProcessRecord app,
1949 String hostingType, String hostingNameStr) {
1950 if (app.pid > 0 && app.pid != MY_PID) {
1951 synchronized (mPidsSelfLocked) {
1952 mPidsSelfLocked.remove(app.pid);
1953 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1954 }
1955 app.pid = 0;
1956 }
1957
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001958 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1959 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 mProcessesOnHold.remove(app);
1961
1962 updateCpuStats();
1963
1964 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1965 mProcDeaths[0] = 0;
1966
1967 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001968 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001971 if (!app.isolated) {
1972 try {
1973 gids = mContext.getPackageManager().getPackageGids(
1974 app.info.packageName);
1975 } catch (PackageManager.NameNotFoundException e) {
1976 Slog.w(TAG, "Unable to retrieve gids", e);
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1980 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1981 && mTopComponent != null
1982 && app.processName.equals(mTopComponent.getPackageName())) {
1983 uid = 0;
1984 }
1985 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1986 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1987 uid = 0;
1988 }
1989 }
1990 int debugFlags = 0;
1991 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1992 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001993 // Also turn on CheckJNI for debuggable apps. It's quite
1994 // awkward to turn on otherwise.
1995 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001997 // Run the app in safe mode if its manifest requests so or the
1998 // system is booted in safe mode.
1999 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2000 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002001 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2004 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2005 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002006 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2007 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 if ("1".equals(SystemProperties.get("debug.assert"))) {
2010 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2011 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002012
2013 // Start the process. It will either succeed and return a result containing
2014 // the PID of the new process, or else throw a RuntimeException.
2015 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002016 app.processName, uid, uid, gids, debugFlags,
2017 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2020 synchronized (bs) {
2021 if (bs.isOnBattery()) {
2022 app.batteryStats.incStartsLocked();
2023 }
2024 }
2025
Jeff Brown3f9dd282011-07-08 20:02:19 -07002026 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 app.processName, hostingType,
2028 hostingNameStr != null ? hostingNameStr : "");
2029
2030 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002031 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002034 StringBuilder buf = mStringBuilder;
2035 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 buf.append("Start proc ");
2037 buf.append(app.processName);
2038 buf.append(" for ");
2039 buf.append(hostingType);
2040 if (hostingNameStr != null) {
2041 buf.append(" ");
2042 buf.append(hostingNameStr);
2043 }
2044 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002045 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 buf.append(" uid=");
2047 buf.append(uid);
2048 buf.append(" gids={");
2049 if (gids != null) {
2050 for (int gi=0; gi<gids.length; gi++) {
2051 if (gi != 0) buf.append(", ");
2052 buf.append(gids[gi]);
2053
2054 }
2055 }
2056 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002057 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002058 app.pid = startResult.pid;
2059 app.usingWrapper = startResult.usingWrapper;
2060 app.removed = false;
2061 synchronized (mPidsSelfLocked) {
2062 this.mPidsSelfLocked.put(startResult.pid, app);
2063 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2064 msg.obj = app;
2065 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2066 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 }
2068 } catch (RuntimeException e) {
2069 // XXX do better error recovery.
2070 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002071 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
2074
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002075 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 if (resumed) {
2077 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2078 } else {
2079 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2080 }
2081 }
2082
Amith Yamasani742a6712011-05-04 14:49:28 -07002083 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002084 if (mHeadless) {
2085 // Added because none of the other calls to ensureBootCompleted seem to fire
2086 // when running headless.
2087 ensureBootCompleted();
2088 return false;
2089 }
2090
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002091 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2092 && mTopAction == null) {
2093 // We are running in factory test mode, but unable to find
2094 // the factory test app, so just sit around displaying the
2095 // error message and don't try to start anything.
2096 return false;
2097 }
2098 Intent intent = new Intent(
2099 mTopAction,
2100 mTopData != null ? Uri.parse(mTopData) : null);
2101 intent.setComponent(mTopComponent);
2102 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2103 intent.addCategory(Intent.CATEGORY_HOME);
2104 }
2105 ActivityInfo aInfo =
2106 intent.resolveActivityInfo(mContext.getPackageManager(),
2107 STOCK_PM_FLAGS);
2108 if (aInfo != null) {
2109 intent.setComponent(new ComponentName(
2110 aInfo.applicationInfo.packageName, aInfo.name));
2111 // Don't do this if the home app is currently being
2112 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002113 aInfo = new ActivityInfo(aInfo);
2114 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2116 aInfo.applicationInfo.uid);
2117 if (app == null || app.instrumentationClass == null) {
2118 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002119 mMainStack.startActivityLocked(null, intent, null, aInfo,
2120 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002121 }
2122 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002123
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002124 return true;
2125 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002126
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002127 /**
2128 * Starts the "new version setup screen" if appropriate.
2129 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002130 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002131 // Only do this once per boot.
2132 if (mCheckedForSetup) {
2133 return;
2134 }
2135
2136 // We will show this screen if the current one is a different
2137 // version than the last one shown, and we are not running in
2138 // low-level factory test mode.
2139 final ContentResolver resolver = mContext.getContentResolver();
2140 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2141 Settings.Secure.getInt(resolver,
2142 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2143 mCheckedForSetup = true;
2144
2145 // See if we should be showing the platform update setup UI.
2146 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2147 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2148 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2149
2150 // We don't allow third party apps to replace this.
2151 ResolveInfo ri = null;
2152 for (int i=0; ris != null && i<ris.size(); i++) {
2153 if ((ris.get(i).activityInfo.applicationInfo.flags
2154 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2155 ri = ris.get(i);
2156 break;
2157 }
2158 }
2159
2160 if (ri != null) {
2161 String vers = ri.activityInfo.metaData != null
2162 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2163 : null;
2164 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2165 vers = ri.activityInfo.applicationInfo.metaData.getString(
2166 Intent.METADATA_SETUP_VERSION);
2167 }
2168 String lastVers = Settings.Secure.getString(
2169 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2170 if (vers != null && !vers.equals(lastVers)) {
2171 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2172 intent.setComponent(new ComponentName(
2173 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002174 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2175 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002176 }
2177 }
2178 }
2179 }
2180
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183 }
2184
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002185 void enforceNotIsolatedCaller(String caller) {
2186 if (UserId.isIsolated(Binder.getCallingUid())) {
2187 throw new SecurityException("Isolated process not allowed to call " + caller);
2188 }
2189 }
2190
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002192 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2195 }
2196 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002197
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002198 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002199 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2200 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002201 synchronized (this) {
2202 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2203 }
2204 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002205
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002206 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002207 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002208 synchronized (this) {
2209 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2210 }
2211 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002212
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002213 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002214 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2215 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002216 synchronized (this) {
2217 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218 }
2219 }
2220
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002221 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002222 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002223 synchronized (this) {
2224 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2225 }
2226 }
2227
2228 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2230 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002231 synchronized (this) {
2232 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2233 }
2234 }
2235
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002236 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002237 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002238
2239 final int identHash = System.identityHashCode(r);
2240 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242
Jeff Sharkeya4620792011-05-20 15:29:23 -07002243 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2244 int i = mProcessObservers.beginBroadcast();
2245 while (i > 0) {
2246 i--;
2247 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2248 if (observer != null) {
2249 try {
2250 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2251 } catch (RemoteException e) {
2252 }
2253 }
2254 }
2255 mProcessObservers.finishBroadcast();
2256 }
2257
2258 private void dispatchProcessDied(int pid, int uid) {
2259 int i = mProcessObservers.beginBroadcast();
2260 while (i > 0) {
2261 i--;
2262 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2263 if (observer != null) {
2264 try {
2265 observer.onProcessDied(pid, uid);
2266 } catch (RemoteException e) {
2267 }
2268 }
2269 }
2270 mProcessObservers.finishBroadcast();
2271 }
2272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002273 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002274 final int N = mPendingActivityLaunches.size();
2275 if (N <= 0) {
2276 return;
2277 }
2278 for (int i=0; i<N; i++) {
2279 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002281 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002282 }
2283 mPendingActivityLaunches.clear();
2284 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002285
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002286 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002287 Intent intent, String resolvedType, IBinder resultTo,
2288 String resultWho, int requestCode, int startFlags,
2289 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002290 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002291 int userId = 0;
2292 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2293 // Requesting home, set the identity to the current user
2294 // HACK!
2295 userId = mCurrentUserId;
2296 } else {
2297 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2298 // the current user's userId
2299 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2300 userId = 0;
2301 } else {
2302 userId = Binder.getOrigCallingUser();
2303 }
2304 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002305 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2307 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002308 }
2309
2310 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002311 Intent intent, String resolvedType, IBinder resultTo,
2312 String resultWho, int requestCode, int startFlags, String profileFile,
2313 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002314 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002315 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002317 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002318 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2319 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002320 return res;
2321 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002322
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002323 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002324 Intent intent, String resolvedType, IBinder resultTo,
2325 String resultWho, int requestCode, int startFlags, Configuration config,
2326 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002327 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002328 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002329 resultTo, resultWho, requestCode, startFlags,
2330 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002331 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002332 }
2333
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002334 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002335 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002336 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002337 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002338 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002339 // Refuse possible leaked file descriptors
2340 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2341 throw new IllegalArgumentException("File descriptors passed in Intent");
2342 }
2343
2344 IIntentSender sender = intent.getTarget();
2345 if (!(sender instanceof PendingIntentRecord)) {
2346 throw new IllegalArgumentException("Bad PendingIntent object");
2347 }
2348
2349 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002350
2351 synchronized (this) {
2352 // If this is coming from the currently resumed activity, it is
2353 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 if (mMainStack.mResumedActivity != null
2355 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002356 Binder.getCallingUid()) {
2357 mAppSwitchesAllowedTime = 0;
2358 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002359 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002360 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2361 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002362 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002363 }
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002366 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 // Refuse possible leaked file descriptors
2368 if (intent != null && intent.hasFileDescriptors() == true) {
2369 throw new IllegalArgumentException("File descriptors passed in Intent");
2370 }
2371
2372 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002373 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2374 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002375 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 return false;
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (r.app == null || r.app.thread == null) {
2379 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002380 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 return false;
2382 }
2383 intent = new Intent(intent);
2384 // The caller is not allowed to change the data.
2385 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2386 // And we are resetting to find the next component...
2387 intent.setComponent(null);
2388
2389 ActivityInfo aInfo = null;
2390 try {
2391 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002392 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002394 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2395 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396
2397 // Look for the original activity in the list...
2398 final int N = resolves != null ? resolves.size() : 0;
2399 for (int i=0; i<N; i++) {
2400 ResolveInfo rInfo = resolves.get(i);
2401 if (rInfo.activityInfo.packageName.equals(r.packageName)
2402 && rInfo.activityInfo.name.equals(r.info.name)) {
2403 // We found the current one... the next matching is
2404 // after it.
2405 i++;
2406 if (i<N) {
2407 aInfo = resolves.get(i).activityInfo;
2408 }
2409 break;
2410 }
2411 }
2412 } catch (RemoteException e) {
2413 }
2414
2415 if (aInfo == null) {
2416 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002417 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 return false;
2419 }
2420
2421 intent.setComponent(new ComponentName(
2422 aInfo.applicationInfo.packageName, aInfo.name));
2423 intent.setFlags(intent.getFlags()&~(
2424 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2425 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2426 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2427 Intent.FLAG_ACTIVITY_NEW_TASK));
2428
2429 // Okay now we need to start the new activity, replacing the
2430 // currently running activity. This is a little tricky because
2431 // we want to start the new one as if the current one is finished,
2432 // but not finish the current one first so that there is no flicker.
2433 // And thus...
2434 final boolean wasFinishing = r.finishing;
2435 r.finishing = true;
2436
2437 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002438 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 final String resultWho = r.resultWho;
2440 final int requestCode = r.requestCode;
2441 r.resultTo = null;
2442 if (resultTo != null) {
2443 resultTo.removeResultsLocked(r, resultWho, requestCode);
2444 }
2445
2446 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002447 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002448 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2449 resultWho, requestCode, -1, r.launchedFromUid, 0,
2450 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 Binder.restoreCallingIdentity(origId);
2452
2453 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002454 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 return false;
2456 }
2457 return true;
2458 }
2459 }
2460
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002461 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002464
2465 // This is so super not safe, that only the system (or okay root)
2466 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002467 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002468 final int callingUid = Binder.getCallingUid();
2469 if (callingUid != 0 && callingUid != Process.myUid()) {
2470 throw new SecurityException(
2471 "startActivityInPackage only available to the system");
2472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473
Amith Yamasani742a6712011-05-04 14:49:28 -07002474 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 resultTo, resultWho, requestCode, startFlags,
2476 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002477 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002478 }
2479
2480 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002481 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002482 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002484 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002485 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002486 }
2487
2488 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002489 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2490 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002491
2492 // This is so super not safe, that only the system (or okay root)
2493 // can do it.
2494 final int callingUid = Binder.getCallingUid();
2495 if (callingUid != 0 && callingUid != Process.myUid()) {
2496 throw new SecurityException(
2497 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002500 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002504 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002506 // Quick case: check if the top-most recent task is the same.
2507 if (N > 0 && mRecentTasks.get(0) == task) {
2508 return;
2509 }
2510 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 for (int i=0; i<N; i++) {
2512 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002513 if (task.userId == tr.userId
2514 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2515 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 mRecentTasks.remove(i);
2517 i--;
2518 N--;
2519 if (task.intent == null) {
2520 // If the new recent task we are adding is not fully
2521 // specified, then replace it with the existing recent task.
2522 task = tr;
2523 }
2524 }
2525 }
2526 if (N >= MAX_RECENT_TASKS) {
2527 mRecentTasks.remove(N-1);
2528 }
2529 mRecentTasks.add(0, task);
2530 }
2531
2532 public void setRequestedOrientation(IBinder token,
2533 int requestedOrientation) {
2534 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002535 ActivityRecord r = mMainStack.isInStackLocked(token);
2536 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 return;
2538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002540 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002542 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002543 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 if (config != null) {
2545 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002546 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002547 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 }
2549 }
2550 Binder.restoreCallingIdentity(origId);
2551 }
2552 }
2553
2554 public int getRequestedOrientation(IBinder token) {
2555 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002556 ActivityRecord r = mMainStack.isInStackLocked(token);
2557 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2559 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002560 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
2562 }
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 /**
2565 * This is the internal entry point for handling Activity.finish().
2566 *
2567 * @param token The Binder token referencing the Activity we want to finish.
2568 * @param resultCode Result code, if any, from this Activity.
2569 * @param resultData Result data (Intent), if any, from this Activity.
2570 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002571 * @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 -08002572 */
2573 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2574 // Refuse possible leaked file descriptors
2575 if (resultData != null && resultData.hasFileDescriptors() == true) {
2576 throw new IllegalArgumentException("File descriptors passed in Intent");
2577 }
2578
2579 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002580 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 if (next != null) {
2584 // ask watcher if this is allowed
2585 boolean resumeOK = true;
2586 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002587 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002589 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591
2592 if (!resumeOK) {
2593 return false;
2594 }
2595 }
2596 }
2597 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 resultData, "app-request");
2600 Binder.restoreCallingIdentity(origId);
2601 return res;
2602 }
2603 }
2604
Dianne Hackborn860755f2010-06-03 18:47:52 -07002605 public final void finishHeavyWeightApp() {
2606 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2607 != PackageManager.PERMISSION_GRANTED) {
2608 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2609 + Binder.getCallingPid()
2610 + ", uid=" + Binder.getCallingUid()
2611 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2612 Slog.w(TAG, msg);
2613 throw new SecurityException(msg);
2614 }
2615
2616 synchronized(this) {
2617 if (mHeavyWeightProcess == null) {
2618 return;
2619 }
2620
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002621 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002622 mHeavyWeightProcess.activities);
2623 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002624 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002625 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002626 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002627 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002629 null, "finish-heavy");
2630 }
2631 }
2632 }
2633
2634 mHeavyWeightProcess = null;
2635 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2636 }
2637 }
2638
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002639 public void crashApplication(int uid, int initialPid, String packageName,
2640 String message) {
2641 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2642 != PackageManager.PERMISSION_GRANTED) {
2643 String msg = "Permission Denial: crashApplication() from pid="
2644 + Binder.getCallingPid()
2645 + ", uid=" + Binder.getCallingUid()
2646 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2647 Slog.w(TAG, msg);
2648 throw new SecurityException(msg);
2649 }
2650
2651 synchronized(this) {
2652 ProcessRecord proc = null;
2653
2654 // Figure out which process to kill. We don't trust that initialPid
2655 // still has any relation to current pids, so must scan through the
2656 // list.
2657 synchronized (mPidsSelfLocked) {
2658 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2659 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002660 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002661 continue;
2662 }
2663 if (p.pid == initialPid) {
2664 proc = p;
2665 break;
2666 }
2667 for (String str : p.pkgList) {
2668 if (str.equals(packageName)) {
2669 proc = p;
2670 }
2671 }
2672 }
2673 }
2674
2675 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002676 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002677 + " initialPid=" + initialPid
2678 + " packageName=" + packageName);
2679 return;
2680 }
2681
2682 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002683 if (proc.pid == Process.myPid()) {
2684 Log.w(TAG, "crashApplication: trying to crash self!");
2685 return;
2686 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002687 long ident = Binder.clearCallingIdentity();
2688 try {
2689 proc.thread.scheduleCrash(message);
2690 } catch (RemoteException e) {
2691 }
2692 Binder.restoreCallingIdentity(ident);
2693 }
2694 }
2695 }
2696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 public final void finishSubActivity(IBinder token, String resultWho,
2698 int requestCode) {
2699 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002700 ActivityRecord self = mMainStack.isInStackLocked(token);
2701 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 return;
2703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704
2705 final long origId = Binder.clearCallingIdentity();
2706
2707 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2709 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 if (r.resultTo == self && r.requestCode == requestCode) {
2711 if ((r.resultWho == null && resultWho == null) ||
2712 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002713 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 Activity.RESULT_CANCELED, null, "request-sub");
2715 }
2716 }
2717 }
2718
2719 Binder.restoreCallingIdentity(origId);
2720 }
2721 }
2722
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002723 public boolean willActivityBeVisible(IBinder token) {
2724 synchronized(this) {
2725 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002726 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2727 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002728 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002729 return true;
2730 }
2731 if (r.fullscreen && !r.finishing) {
2732 return false;
2733 }
2734 }
2735 return true;
2736 }
2737 }
2738
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002739 public void overridePendingTransition(IBinder token, String packageName,
2740 int enterAnim, int exitAnim) {
2741 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002742 ActivityRecord self = mMainStack.isInStackLocked(token);
2743 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002744 return;
2745 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002746
2747 final long origId = Binder.clearCallingIdentity();
2748
2749 if (self.state == ActivityState.RESUMED
2750 || self.state == ActivityState.PAUSING) {
2751 mWindowManager.overridePendingAppTransition(packageName,
2752 enterAnim, exitAnim);
2753 }
2754
2755 Binder.restoreCallingIdentity(origId);
2756 }
2757 }
2758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 * Main function for removing an existing process from the activity manager
2761 * as a result of that process going away. Clears out all connections
2762 * to the process.
2763 */
2764 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002765 boolean restarting, boolean allowRestart) {
2766 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002768 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
2770
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002771 if (mProfileProc == app) {
2772 clearProfilerLocked();
2773 }
2774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002776 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2777 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2778 mMainStack.mPausingActivity = null;
2779 }
2780 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2781 mMainStack.mLastPausedActivity = null;
2782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783
2784 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002785 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786
2787 boolean atTop = true;
2788 boolean hasVisibleActivities = false;
2789
2790 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002791 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002792 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 TAG, "Removing app " + app + " from history with " + i + " entries");
2794 while (i > 0) {
2795 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002796 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002797 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2799 if (r.app == app) {
2800 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002801 if (ActivityStack.DEBUG_ADD_REMOVE) {
2802 RuntimeException here = new RuntimeException("here");
2803 here.fillInStackTrace();
2804 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2805 + ": haveState=" + r.haveState
2806 + " stateNotNeeded=" + r.stateNotNeeded
2807 + " finishing=" + r.finishing
2808 + " state=" + r.state, here);
2809 }
2810 if (!r.finishing) {
2811 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002812 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2813 System.identityHashCode(r),
2814 r.task.taskId, r.shortComponentName,
2815 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002816 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002817 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818
2819 } else {
2820 // We have the current state for this activity, so
2821 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002822 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 TAG, "Keeping entry, setting app to null");
2824 if (r.visible) {
2825 hasVisibleActivities = true;
2826 }
2827 r.app = null;
2828 r.nowVisible = false;
2829 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002830 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2831 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 r.icicle = null;
2833 }
2834 }
2835
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002836 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 }
2838 atTop = false;
2839 }
2840
2841 app.activities.clear();
2842
2843 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002844 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 + " running instrumentation " + app.instrumentationClass);
2846 Bundle info = new Bundle();
2847 info.putString("shortMsg", "Process crashed.");
2848 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2849 }
2850
2851 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // If there was nothing to resume, and we are not already
2854 // restarting this process, but there is a visible activity that
2855 // is hosted by the process... then make sure all visible
2856 // activities are running, taking care of restarting this
2857 // process.
2858 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002859 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861 }
2862 }
2863 }
2864
2865 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2866 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002868 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2869 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2871 return i;
2872 }
2873 }
2874 return -1;
2875 }
2876
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002877 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 IApplicationThread thread) {
2879 if (thread == null) {
2880 return null;
2881 }
2882
2883 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002884 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 }
2886
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002887 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 IApplicationThread thread) {
2889
2890 mProcDeaths[0]++;
2891
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002892 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2893 synchronized (stats) {
2894 stats.noteProcessDiedLocked(app.info.uid, pid);
2895 }
2896
Magnus Edlund7bb25812010-02-24 15:45:06 +01002897 // Clean up already done if the process has been re-started.
2898 if (app.pid == pid && app.thread != null &&
2899 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002900 if (!app.killedBackground) {
2901 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2902 + ") has died.");
2903 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002904 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002905 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 TAG, "Dying app: " + app + ", pid: " + pid
2907 + ", thread: " + thread.asBinder());
2908 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002909 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910
2911 if (doLowMem) {
2912 // If there are no longer any background processes running,
2913 // and the app that died was not running instrumentation,
2914 // then tell everyone we are now low on memory.
2915 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002916 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2917 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002918 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 haveBg = true;
2920 break;
2921 }
2922 }
2923
2924 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002925 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002926 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002927 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2928 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002929 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002930 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2931 // The low memory report is overriding any current
2932 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002933 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002934 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002935 rec.lastRequestedGc = 0;
2936 } else {
2937 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002939 rec.reportLowMemory = true;
2940 rec.lastLowMemory = now;
2941 mProcessesToGc.remove(rec);
2942 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 }
2944 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002945 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002946 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 }
2948 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002949 } else if (app.pid != pid) {
2950 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002951 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002952 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002953 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002954 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002955 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 + thread.asBinder());
2957 }
2958 }
2959
Dan Egnor42471dd2010-01-07 17:25:22 -08002960 /**
2961 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002962 * @param clearTraces causes the dump file to be erased prior to the new
2963 * traces being written, if true; when false, the new traces will be
2964 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002965 * @param firstPids of dalvik VM processes to dump stack traces for first
2966 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002967 * @return file containing stack traces, or null if no dump file is configured
2968 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002969 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2970 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002971 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2972 if (tracesPath == null || tracesPath.length() == 0) {
2973 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002975
2976 File tracesFile = new File(tracesPath);
2977 try {
2978 File tracesDir = tracesFile.getParentFile();
2979 if (!tracesDir.exists()) tracesFile.mkdirs();
2980 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2981
Christopher Tate6ee412d2010-05-28 12:01:56 -07002982 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002983 tracesFile.createNewFile();
2984 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2985 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002986 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002987 return null;
2988 }
2989
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002990 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2991 return tracesFile;
2992 }
2993
2994 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2995 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002996 // Use a FileObserver to detect when traces finish writing.
2997 // The order of traces is considered important to maintain for legibility.
2998 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2999 public synchronized void onEvent(int event, String path) { notify(); }
3000 };
3001
3002 try {
3003 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003004
3005 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003006 if (firstPids != null) {
3007 try {
3008 int num = firstPids.size();
3009 for (int i = 0; i < num; i++) {
3010 synchronized (observer) {
3011 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3012 observer.wait(200); // Wait for write-close, give up after 200msec
3013 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003014 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003015 } catch (InterruptedException e) {
3016 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003017 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003018 }
3019
3020 // Next measure CPU usage.
3021 if (processStats != null) {
3022 processStats.init();
3023 System.gc();
3024 processStats.update();
3025 try {
3026 synchronized (processStats) {
3027 processStats.wait(500); // measure over 1/2 second.
3028 }
3029 } catch (InterruptedException e) {
3030 }
3031 processStats.update();
3032
3033 // We'll take the stack crawls of just the top apps using CPU.
3034 final int N = processStats.countWorkingStats();
3035 int numProcs = 0;
3036 for (int i=0; i<N && numProcs<5; i++) {
3037 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3038 if (lastPids.indexOfKey(stats.pid) >= 0) {
3039 numProcs++;
3040 try {
3041 synchronized (observer) {
3042 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3043 observer.wait(200); // Wait for write-close, give up after 200msec
3044 }
3045 } catch (InterruptedException e) {
3046 Log.wtf(TAG, e);
3047 }
3048
3049 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003050 }
3051 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003052
Dan Egnor42471dd2010-01-07 17:25:22 -08003053 } finally {
3054 observer.stopWatching();
3055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 }
3057
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003058 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003059 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003060 return;
3061 }
3062 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3063 if (tracesPath == null || tracesPath.length() == 0) {
3064 return;
3065 }
3066
3067 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3068 StrictMode.allowThreadDiskWrites();
3069 try {
3070 final File tracesFile = new File(tracesPath);
3071 final File tracesDir = tracesFile.getParentFile();
3072 final File tracesTmp = new File(tracesDir, "__tmp__");
3073 try {
3074 if (!tracesDir.exists()) tracesFile.mkdirs();
3075 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3076
3077 if (tracesFile.exists()) {
3078 tracesTmp.delete();
3079 tracesFile.renameTo(tracesTmp);
3080 }
3081 StringBuilder sb = new StringBuilder();
3082 Time tobj = new Time();
3083 tobj.set(System.currentTimeMillis());
3084 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3085 sb.append(": ");
3086 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3087 sb.append(" since ");
3088 sb.append(msg);
3089 FileOutputStream fos = new FileOutputStream(tracesFile);
3090 fos.write(sb.toString().getBytes());
3091 if (app == null) {
3092 fos.write("\n*** No application process!".getBytes());
3093 }
3094 fos.close();
3095 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3096 } catch (IOException e) {
3097 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3098 return;
3099 }
3100
3101 if (app != null) {
3102 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3103 firstPids.add(app.pid);
3104 dumpStackTraces(tracesPath, firstPids, null, null);
3105 }
3106
3107 File lastTracesFile = null;
3108 File curTracesFile = null;
3109 for (int i=9; i>=0; i--) {
3110 String name = String.format("slow%02d.txt", i);
3111 curTracesFile = new File(tracesDir, name);
3112 if (curTracesFile.exists()) {
3113 if (lastTracesFile != null) {
3114 curTracesFile.renameTo(lastTracesFile);
3115 } else {
3116 curTracesFile.delete();
3117 }
3118 }
3119 lastTracesFile = curTracesFile;
3120 }
3121 tracesFile.renameTo(curTracesFile);
3122 if (tracesTmp.exists()) {
3123 tracesTmp.renameTo(tracesFile);
3124 }
3125 } finally {
3126 StrictMode.setThreadPolicy(oldPolicy);
3127 }
3128 }
3129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003130 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3131 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003132 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3133 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3134
Dianne Hackborn287952c2010-09-22 22:34:31 -07003135 if (mController != null) {
3136 try {
3137 // 0 == continue, -1 = kill process immediately
3138 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3139 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3140 } catch (RemoteException e) {
3141 mController = null;
3142 }
3143 }
3144
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003145 long anrTime = SystemClock.uptimeMillis();
3146 if (MONITOR_CPU_USAGE) {
3147 updateCpuStatsNow();
3148 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003149
3150 synchronized (this) {
3151 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3152 if (mShuttingDown) {
3153 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3154 return;
3155 } else if (app.notResponding) {
3156 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3157 return;
3158 } else if (app.crashing) {
3159 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3160 return;
3161 }
3162
3163 // In case we come through here for the same app before completing
3164 // this one, mark as anring now so we will bail out.
3165 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003166
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003167 // Log the ANR to the event log.
3168 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3169 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003170
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003171 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003172 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003173
3174 int parentPid = app.pid;
3175 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003176 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003177
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003178 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003179
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003180 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3181 ProcessRecord r = mLruProcesses.get(i);
3182 if (r != null && r.thread != null) {
3183 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003184 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3185 if (r.persistent) {
3186 firstPids.add(pid);
3187 } else {
3188 lastPids.put(pid, Boolean.TRUE);
3189 }
3190 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 }
3193 }
3194
Dan Egnor42471dd2010-01-07 17:25:22 -08003195 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003196 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003197 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003198 info.append("ANR in ").append(app.processName);
3199 if (activity != null && activity.shortComponentName != null) {
3200 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003201 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003202 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003204 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003206 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003207 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209
Dianne Hackborn287952c2010-09-22 22:34:31 -07003210 final ProcessStats processStats = new ProcessStats(true);
3211
3212 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3213
Dan Egnor42471dd2010-01-07 17:25:22 -08003214 String cpuInfo = null;
3215 if (MONITOR_CPU_USAGE) {
3216 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003217 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003218 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003219 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003220 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003221 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
3223
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003224 info.append(processStats.printCurrentState(anrTime));
3225
Joe Onorato8a9b2202010-02-26 18:56:32 -08003226 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003227 if (tracesFile == null) {
3228 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3229 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3230 }
3231
Jeff Sharkeya353d262011-10-28 11:12:06 -07003232 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3233 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003234
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003235 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003237 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3238 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003240 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3241 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 }
3243 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003244 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 }
3246 }
3247
Dan Egnor42471dd2010-01-07 17:25:22 -08003248 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3249 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3250 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003251
3252 synchronized (this) {
3253 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003254 Slog.w(TAG, "Killing " + app + ": background ANR");
3255 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3256 app.processName, app.setAdj, "background ANR");
3257 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003258 return;
3259 }
3260
3261 // Set the app's notResponding state, and look up the errorReportReceiver
3262 makeAppNotRespondingLocked(app,
3263 activity != null ? activity.shortComponentName : null,
3264 annotation != null ? "ANR " + annotation : "ANR",
3265 info.toString());
3266
3267 // Bring up the infamous App Not Responding dialog
3268 Message msg = Message.obtain();
3269 HashMap map = new HashMap();
3270 msg.what = SHOW_NOT_RESPONDING_MSG;
3271 msg.obj = map;
3272 map.put("app", app);
3273 if (activity != null) {
3274 map.put("activity", activity);
3275 }
3276
3277 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
3280
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003281 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3282 if (!mLaunchWarningShown) {
3283 mLaunchWarningShown = true;
3284 mHandler.post(new Runnable() {
3285 @Override
3286 public void run() {
3287 synchronized (ActivityManagerService.this) {
3288 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3289 d.show();
3290 mHandler.postDelayed(new Runnable() {
3291 @Override
3292 public void run() {
3293 synchronized (ActivityManagerService.this) {
3294 d.dismiss();
3295 mLaunchWarningShown = false;
3296 }
3297 }
3298 }, 4000);
3299 }
3300 }
3301 });
3302 }
3303 }
3304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003306 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003307 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 int uid = Binder.getCallingUid();
3309 int pid = Binder.getCallingPid();
3310 long callingId = Binder.clearCallingIdentity();
3311 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003312 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 int pkgUid = -1;
3314 synchronized(this) {
3315 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003316 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 } catch (RemoteException e) {
3318 }
3319 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003320 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 return false;
3322 }
3323 if (uid == pkgUid || checkComponentPermission(
3324 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003325 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003327 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 } else {
3329 throw new SecurityException(pid+" does not have permission:"+
3330 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3331 "for process:"+packageName);
3332 }
3333 }
3334
3335 try {
3336 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003337 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3339 Uri.fromParts("package", packageName, null));
3340 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003341 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003342 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 } catch (RemoteException e) {
3344 }
3345 } finally {
3346 Binder.restoreCallingIdentity(callingId);
3347 }
3348 return true;
3349 }
3350
Dianne Hackborn03abb812010-01-04 18:43:19 -08003351 public void killBackgroundProcesses(final String packageName) {
3352 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3353 != PackageManager.PERMISSION_GRANTED &&
3354 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3355 != PackageManager.PERMISSION_GRANTED) {
3356 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 + Binder.getCallingPid()
3358 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003359 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003360 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 throw new SecurityException(msg);
3362 }
3363
Amith Yamasani483f3b02012-03-13 16:08:00 -07003364 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 long callingId = Binder.clearCallingIdentity();
3366 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003367 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 int pkgUid = -1;
3369 synchronized(this) {
3370 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003371 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 } catch (RemoteException e) {
3373 }
3374 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003375 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 return;
3377 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003378 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003379 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3380 }
3381 } finally {
3382 Binder.restoreCallingIdentity(callingId);
3383 }
3384 }
3385
3386 public void killAllBackgroundProcesses() {
3387 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3388 != PackageManager.PERMISSION_GRANTED) {
3389 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3390 + Binder.getCallingPid()
3391 + ", uid=" + Binder.getCallingUid()
3392 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3393 Slog.w(TAG, msg);
3394 throw new SecurityException(msg);
3395 }
3396
3397 long callingId = Binder.clearCallingIdentity();
3398 try {
3399 synchronized(this) {
3400 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3401 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3402 final int NA = apps.size();
3403 for (int ia=0; ia<NA; ia++) {
3404 ProcessRecord app = apps.valueAt(ia);
3405 if (app.persistent) {
3406 // we don't kill persistent processes
3407 continue;
3408 }
3409 if (app.removed) {
3410 procs.add(app);
3411 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3412 app.removed = true;
3413 procs.add(app);
3414 }
3415 }
3416 }
3417
3418 int N = procs.size();
3419 for (int i=0; i<N; i++) {
3420 removeProcessLocked(procs.get(i), false, true, "kill all background");
3421 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003422 }
3423 } finally {
3424 Binder.restoreCallingIdentity(callingId);
3425 }
3426 }
3427
3428 public void forceStopPackage(final String packageName) {
3429 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3430 != PackageManager.PERMISSION_GRANTED) {
3431 String msg = "Permission Denial: forceStopPackage() from pid="
3432 + Binder.getCallingPid()
3433 + ", uid=" + Binder.getCallingUid()
3434 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003435 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003436 throw new SecurityException(msg);
3437 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003438 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003439 long callingId = Binder.clearCallingIdentity();
3440 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003441 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003442 int pkgUid = -1;
3443 synchronized(this) {
3444 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003445 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003446 } catch (RemoteException e) {
3447 }
3448 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003449 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003450 return;
3451 }
3452 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003453 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003454 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003455 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003456 } catch (IllegalArgumentException e) {
3457 Slog.w(TAG, "Failed trying to unstop package "
3458 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 }
3461 } finally {
3462 Binder.restoreCallingIdentity(callingId);
3463 }
3464 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003465
3466 /*
3467 * The pkg name and uid have to be specified.
3468 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3469 */
3470 public void killApplicationWithUid(String pkg, int uid) {
3471 if (pkg == null) {
3472 return;
3473 }
3474 // Make sure the uid is valid.
3475 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003476 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003477 return;
3478 }
3479 int callerUid = Binder.getCallingUid();
3480 // Only the system server can kill an application
3481 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003482 // Post an aysnc message to kill the application
3483 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3484 msg.arg1 = uid;
3485 msg.arg2 = 0;
3486 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003487 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003488 } else {
3489 throw new SecurityException(callerUid + " cannot kill pkg: " +
3490 pkg);
3491 }
3492 }
3493
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003494 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003495 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003496 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003497 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003498 if (reason != null) {
3499 intent.putExtra("reason", reason);
3500 }
3501
3502 final int uid = Binder.getCallingUid();
3503 final long origId = Binder.clearCallingIdentity();
3504 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003505 mWindowManager.closeSystemDialogs(reason);
3506
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003507 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003508 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003509 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003510 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003511 Activity.RESULT_CANCELED, null, "close-sys");
3512 }
3513 }
3514
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003515 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003516 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003517 }
3518 Binder.restoreCallingIdentity(origId);
3519 }
3520
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003521 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003522 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003523 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003524 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3525 for (int i=pids.length-1; i>=0; i--) {
3526 infos[i] = new Debug.MemoryInfo();
3527 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003528 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003529 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003530 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003531
Dianne Hackbornb437e092011-08-05 17:50:29 -07003532 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003533 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003534 long[] pss = new long[pids.length];
3535 for (int i=pids.length-1; i>=0; i--) {
3536 pss[i] = Debug.getPss(pids[i]);
3537 }
3538 return pss;
3539 }
3540
Christopher Tate5e1ab332009-09-01 20:32:49 -07003541 public void killApplicationProcess(String processName, int uid) {
3542 if (processName == null) {
3543 return;
3544 }
3545
3546 int callerUid = Binder.getCallingUid();
3547 // Only the system server can kill an application
3548 if (callerUid == Process.SYSTEM_UID) {
3549 synchronized (this) {
3550 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003551 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003552 try {
3553 app.thread.scheduleSuicide();
3554 } catch (RemoteException e) {
3555 // If the other end already died, then our work here is done.
3556 }
3557 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003558 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003559 + processName + " / " + uid);
3560 }
3561 }
3562 } else {
3563 throw new SecurityException(callerUid + " cannot kill app process: " +
3564 processName);
3565 }
3566 }
3567
Dianne Hackborn03abb812010-01-04 18:43:19 -08003568 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003569 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3571 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003572 if (!mProcessesReady) {
3573 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 intent.putExtra(Intent.EXTRA_UID, uid);
3576 broadcastIntentLocked(null, null, intent,
3577 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003578 false, false,
3579 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003582 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003583 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003584 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586
Dianne Hackborn03abb812010-01-04 18:43:19 -08003587 // Remove all processes this package may have touched: all with the
3588 // same UID (except for the system or root user), and all whose name
3589 // matches the package name.
3590 final String procNamePrefix = packageName + ":";
3591 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3592 final int NA = apps.size();
3593 for (int ia=0; ia<NA; ia++) {
3594 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003595 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003596 // we don't kill persistent processes
3597 continue;
3598 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003600 if (doit) {
3601 procs.add(app);
3602 }
Amith Yamasani13593602012-03-22 16:16:17 -07003603 // If uid is specified and the uid and process name match
3604 // Or, the uid is not specified and the process name matches
3605 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003606 || ((app.processName.equals(packageName)
3607 || app.processName.startsWith(procNamePrefix))
3608 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003609 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003610 if (!doit) {
3611 return true;
3612 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003613 app.removed = true;
3614 procs.add(app);
3615 }
3616 }
3617 }
3618 }
3619
3620 int N = procs.size();
3621 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003622 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003623 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003624 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003625 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003626
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003627 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003628 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003629 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003630 int i;
3631 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 if (uid < 0) {
3634 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003635 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 } catch (RemoteException e) {
3637 }
3638 }
3639
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003640 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003641 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003642
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3644 while (badApps.hasNext()) {
3645 SparseArray<Long> ba = badApps.next();
3646 if (ba.get(uid) != null) {
3647 badApps.remove();
3648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 }
3650 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003651
3652 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003653 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003655 TaskRecord lastTask = null;
3656 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003657 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003658 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003659 if (r.userId == userId
3660 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003661 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003662 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003663 if (r.finishing) {
3664 // If this activity is just finishing, then it is not
3665 // interesting as far as something to stop.
3666 continue;
3667 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003668 return true;
3669 }
3670 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003671 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003672 if (samePackage) {
3673 if (r.app != null) {
3674 r.app.removed = true;
3675 }
3676 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003678 lastTask = r.task;
3679 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003680 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003681 i--;
3682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
3684 }
3685
3686 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003687 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003688 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003689 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003690 if (!doit) {
3691 return true;
3692 }
3693 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003694 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 if (service.app != null) {
3696 service.app.removed = true;
3697 }
3698 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003699 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 services.add(service);
3701 }
3702 }
3703
3704 N = services.size();
3705 for (i=0; i<N; i++) {
3706 bringDownServiceLocked(services.get(i), true);
3707 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003708
3709 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003710 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003711 if (provider.info.packageName.equals(name)
3712 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3713 if (!doit) {
3714 return true;
3715 }
3716 didSomething = true;
3717 providers.add(provider);
3718 }
3719 }
3720
3721 N = providers.size();
3722 for (i=0; i<N; i++) {
3723 removeDyingProviderLocked(null, providers.get(i));
3724 }
3725
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003726 if (doit) {
3727 if (purgeCache) {
3728 AttributeCache ac = AttributeCache.instance();
3729 if (ac != null) {
3730 ac.removePackage(name);
3731 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003732 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003733 if (mBooted) {
3734 mMainStack.resumeTopActivityLocked(null);
3735 mMainStack.scheduleIdleLocked();
3736 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003737 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003738
3739 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 }
3741
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003742 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003743 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003745 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003746 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003747 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 + "/" + uid + ")");
3749
3750 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003751 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003752 if (mHeavyWeightProcess == app) {
3753 mHeavyWeightProcess = null;
3754 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 boolean needRestart = false;
3757 if (app.pid > 0 && app.pid != MY_PID) {
3758 int pid = app.pid;
3759 synchronized (mPidsSelfLocked) {
3760 mPidsSelfLocked.remove(pid);
3761 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3762 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003763 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003764 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003765 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003766 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003768 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003770 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 } else {
3772 needRestart = true;
3773 }
3774 }
3775 } else {
3776 mRemovedProcesses.add(app);
3777 }
3778
3779 return needRestart;
3780 }
3781
3782 private final void processStartTimedOutLocked(ProcessRecord app) {
3783 final int pid = app.pid;
3784 boolean gone = false;
3785 synchronized (mPidsSelfLocked) {
3786 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3787 if (knownApp != null && knownApp.thread == null) {
3788 mPidsSelfLocked.remove(pid);
3789 gone = true;
3790 }
3791 }
3792
3793 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003794 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003795 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003796 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003797 mProcessNames.remove(app.processName, app.uid);
3798 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003799 if (mHeavyWeightProcess == app) {
3800 mHeavyWeightProcess = null;
3801 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3802 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003803 // Take care of any launching providers waiting for this process.
3804 checkAppInLaunchingProvidersLocked(app, true);
3805 // Take care of any services that are waiting for the process.
3806 for (int i=0; i<mPendingServices.size(); i++) {
3807 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003808 if ((app.uid == sr.appInfo.uid
3809 && app.processName.equals(sr.processName))
3810 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003811 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003812 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003813 mPendingServices.remove(i);
3814 i--;
3815 bringDownServiceLocked(sr, true);
3816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003818 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3819 app.processName, app.setAdj, "start timeout");
3820 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003821 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003822 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003823 try {
3824 IBackupManager bm = IBackupManager.Stub.asInterface(
3825 ServiceManager.getService(Context.BACKUP_SERVICE));
3826 bm.agentDisconnected(app.info.packageName);
3827 } catch (RemoteException e) {
3828 // Can't happen; the backup manager is local
3829 }
3830 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003831 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003832 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003833 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003836 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 }
3838 }
3839
3840 private final boolean attachApplicationLocked(IApplicationThread thread,
3841 int pid) {
3842
3843 // Find the application record that is being attached... either via
3844 // the pid if we are running in multiple processes, or just pull the
3845 // next app record if we are emulating process with anonymous threads.
3846 ProcessRecord app;
3847 if (pid != MY_PID && pid >= 0) {
3848 synchronized (mPidsSelfLocked) {
3849 app = mPidsSelfLocked.get(pid);
3850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 } else {
3852 app = null;
3853 }
3854
3855 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003856 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003858 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003860 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 } else {
3862 try {
3863 thread.scheduleExit();
3864 } catch (Exception e) {
3865 // Ignore exceptions.
3866 }
3867 }
3868 return false;
3869 }
3870
3871 // If this application record is still attached to a previous
3872 // process, clean it up now.
3873 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003874 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 }
3876
3877 // Tell the process all about itself.
3878
Joe Onorato8a9b2202010-02-26 18:56:32 -08003879 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 TAG, "Binding process pid " + pid + " to record " + app);
3881
3882 String processName = app.processName;
3883 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003884 AppDeathRecipient adr = new AppDeathRecipient(
3885 app, pid, thread);
3886 thread.asBinder().linkToDeath(adr, 0);
3887 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 } catch (RemoteException e) {
3889 app.resetPackageList();
3890 startProcessLocked(app, "link fail", processName);
3891 return false;
3892 }
3893
Doug Zongker2bec3d42009-12-04 12:52:44 -08003894 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895
3896 app.thread = thread;
3897 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003898 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3899 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 app.forcingToForeground = null;
3901 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003902 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 app.debugging = false;
3904
3905 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3906
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003907 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003908 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003910 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003911 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003912 }
3913
Joe Onorato8a9b2202010-02-26 18:56:32 -08003914 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 TAG, "New app record " + app
3916 + " thread=" + thread.asBinder() + " pid=" + pid);
3917 try {
3918 int testMode = IApplicationThread.DEBUG_OFF;
3919 if (mDebugApp != null && mDebugApp.equals(processName)) {
3920 testMode = mWaitForDebugger
3921 ? IApplicationThread.DEBUG_WAIT
3922 : IApplicationThread.DEBUG_ON;
3923 app.debugging = true;
3924 if (mDebugTransient) {
3925 mDebugApp = mOrigDebugApp;
3926 mWaitForDebugger = mOrigWaitForDebugger;
3927 }
3928 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003929 String profileFile = app.instrumentationProfileFile;
3930 ParcelFileDescriptor profileFd = null;
3931 boolean profileAutoStop = false;
3932 if (mProfileApp != null && mProfileApp.equals(processName)) {
3933 mProfileProc = app;
3934 profileFile = mProfileFile;
3935 profileFd = mProfileFd;
3936 profileAutoStop = mAutoStopProfiler;
3937 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003938 boolean enableOpenGlTrace = false;
3939 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3940 enableOpenGlTrace = true;
3941 mOpenGlTraceApp = null;
3942 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003943
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 // If the app is being launched for restore or full backup, set it up specially
3945 boolean isRestrictedBackupMode = false;
3946 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3947 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003948 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003949 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3950 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003951
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003952 ensurePackageDexOpt(app.instrumentationInfo != null
3953 ? app.instrumentationInfo.packageName
3954 : app.info.packageName);
3955 if (app.instrumentationClass != null) {
3956 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003957 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003958 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003959 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003960 ApplicationInfo appInfo = app.instrumentationInfo != null
3961 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003962 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003963 if (profileFd != null) {
3964 profileFd = profileFd.dup();
3965 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003966 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003967 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003968 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3969 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003970 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003971 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003972 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003973 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 } catch (Exception e) {
3975 // todo: Yikes! What should we do? For now we will try to
3976 // start another process, but that could easily get us in
3977 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003978 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979
3980 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003981 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 startProcessLocked(app, "bind fail", processName);
3983 return false;
3984 }
3985
3986 // Remove this record from the list of starting applications.
3987 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003988 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3989 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 mProcessesOnHold.remove(app);
3991
3992 boolean badApp = false;
3993 boolean didSomething = false;
3994
3995 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003996 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003997 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003998 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 && processName.equals(hr.processName)) {
4000 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004001 if (mHeadless) {
4002 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4003 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 didSomething = true;
4005 }
4006 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004007 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 + hr.intent.getComponent().flattenToShortString(), e);
4009 badApp = true;
4010 }
4011 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004012 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 }
4014 }
4015
4016 // Find any services that should be running in this process...
4017 if (!badApp && mPendingServices.size() > 0) {
4018 ServiceRecord sr = null;
4019 try {
4020 for (int i=0; i<mPendingServices.size(); i++) {
4021 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004022 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4023 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 continue;
4025 }
4026
4027 mPendingServices.remove(i);
4028 i--;
4029 realStartServiceLocked(sr, app);
4030 didSomething = true;
4031 }
4032 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004033 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 + sr.shortName, e);
4035 badApp = true;
4036 }
4037 }
4038
Christopher Tatef46723b2012-01-26 14:19:24 -08004039 // Check if a next-broadcast receiver is in this process...
4040 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004042 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004044 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 }
4047 }
4048
Christopher Tate181fafa2009-05-14 11:12:14 -07004049 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004050 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004051 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004052 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004053 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004054 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4055 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4056 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004057 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004058 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004059 e.printStackTrace();
4060 }
4061 }
4062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 if (badApp) {
4064 // todo: Also need to kill application to deal with all
4065 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004066 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 return false;
4068 }
4069
4070 if (!didSomething) {
4071 updateOomAdjLocked();
4072 }
4073
4074 return true;
4075 }
4076
4077 public final void attachApplication(IApplicationThread thread) {
4078 synchronized (this) {
4079 int callingPid = Binder.getCallingPid();
4080 final long origId = Binder.clearCallingIdentity();
4081 attachApplicationLocked(thread, callingPid);
4082 Binder.restoreCallingIdentity(origId);
4083 }
4084 }
4085
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004086 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004088 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4089 if (stopProfiling) {
4090 synchronized (this) {
4091 if (mProfileProc == r.app) {
4092 if (mProfileFd != null) {
4093 try {
4094 mProfileFd.close();
4095 } catch (IOException e) {
4096 }
4097 clearProfilerLocked();
4098 }
4099 }
4100 }
4101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 Binder.restoreCallingIdentity(origId);
4103 }
4104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004106 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004107 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 mWindowManager.enableScreenAfterBoot();
4109 }
4110
Dianne Hackborn661cd522011-08-22 00:26:20 -07004111 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004112 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004113 mWindowManager.showBootMessage(msg, always);
4114 }
4115
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004116 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004117 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004118 synchronized (this) {
4119 mMainStack.dismissKeyguardOnNextActivityLocked();
4120 }
4121 }
4122
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004123 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004124 IntentFilter pkgFilter = new IntentFilter();
4125 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4126 pkgFilter.addDataScheme("package");
4127 mContext.registerReceiver(new BroadcastReceiver() {
4128 @Override
4129 public void onReceive(Context context, Intent intent) {
4130 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4131 if (pkgs != null) {
4132 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004133 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004134 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4135 setResultCode(Activity.RESULT_OK);
4136 return;
4137 }
4138 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004139 }
4140 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004141 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004142 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004143
4144 IntentFilter userFilter = new IntentFilter();
4145 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4146 mContext.registerReceiver(new BroadcastReceiver() {
4147 @Override
4148 public void onReceive(Context context, Intent intent) {
4149 onUserRemoved(intent);
4150 }
4151 }, userFilter);
4152
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004153 synchronized (this) {
4154 // Ensure that any processes we had put on hold are now started
4155 // up.
4156 final int NP = mProcessesOnHold.size();
4157 if (NP > 0) {
4158 ArrayList<ProcessRecord> procs =
4159 new ArrayList<ProcessRecord>(mProcessesOnHold);
4160 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004161 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4162 + procs.get(ip));
4163 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004164 }
4165 }
4166
4167 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004168 // Start looking for apps that are abusing wake locks.
4169 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004170 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004171 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004172 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004173 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004174 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004175 broadcastIntentLocked(null, null,
4176 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4177 null, null, 0, null, null,
4178 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004179 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004180 }
4181 }
4182 }
4183
4184 final void ensureBootCompleted() {
4185 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004186 boolean enableScreen;
4187 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004188 booting = mBooting;
4189 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004190 enableScreen = !mBooted;
4191 mBooted = true;
4192 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004193
4194 if (booting) {
4195 finishBooting();
4196 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004197
4198 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004199 enableScreenAfterBoot();
4200 }
4201 }
4202
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004203 public final void activityPaused(IBinder token) {
4204 final long origId = Binder.clearCallingIdentity();
4205 mMainStack.activityPaused(token, false);
4206 Binder.restoreCallingIdentity(origId);
4207 }
4208
4209 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4210 CharSequence description) {
4211 if (localLOGV) Slog.v(
4212 TAG, "Activity stopped: token=" + token);
4213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 // Refuse possible leaked file descriptors
4215 if (icicle != null && icicle.hasFileDescriptors()) {
4216 throw new IllegalArgumentException("File descriptors passed in Bundle");
4217 }
4218
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004219 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220
4221 final long origId = Binder.clearCallingIdentity();
4222
4223 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004224 r = mMainStack.isInStackLocked(token);
4225 if (r != null) {
4226 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 }
4228 }
4229
4230 if (r != null) {
4231 sendPendingThumbnail(r, null, null, null, false);
4232 }
4233
4234 trimApplications();
4235
4236 Binder.restoreCallingIdentity(origId);
4237 }
4238
4239 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004240 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004241 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 }
4243
4244 public String getCallingPackage(IBinder token) {
4245 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004246 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004247 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
4249 }
4250
4251 public ComponentName getCallingActivity(IBinder token) {
4252 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004253 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 return r != null ? r.intent.getComponent() : null;
4255 }
4256 }
4257
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004258 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004259 ActivityRecord r = mMainStack.isInStackLocked(token);
4260 if (r == null) {
4261 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004263 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 }
4265
4266 public ComponentName getActivityClassForToken(IBinder token) {
4267 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004268 ActivityRecord r = mMainStack.isInStackLocked(token);
4269 if (r == null) {
4270 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004272 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
4274 }
4275
4276 public String getPackageForToken(IBinder token) {
4277 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004278 ActivityRecord r = mMainStack.isInStackLocked(token);
4279 if (r == null) {
4280 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004282 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
4284 }
4285
4286 public IIntentSender getIntentSender(int type,
4287 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004288 int requestCode, Intent[] intents, String[] resolvedTypes,
4289 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004290 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004292 if (intents != null) {
4293 if (intents.length < 1) {
4294 throw new IllegalArgumentException("Intents array length must be >= 1");
4295 }
4296 for (int i=0; i<intents.length; i++) {
4297 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004298 if (intent != null) {
4299 if (intent.hasFileDescriptors()) {
4300 throw new IllegalArgumentException("File descriptors passed in Intent");
4301 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004302 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004303 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4304 throw new IllegalArgumentException(
4305 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4306 }
4307 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004308 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004309 }
4310 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004311 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004312 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004313 }
4314 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004315 if (options != null) {
4316 if (options.hasFileDescriptors()) {
4317 throw new IllegalArgumentException("File descriptors passed in options");
4318 }
4319 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 synchronized(this) {
4322 int callingUid = Binder.getCallingUid();
4323 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004324 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004325 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004326 .getPackageUid(packageName, UserId.getUserId(callingUid));
4327 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 String msg = "Permission Denial: getIntentSender() from pid="
4329 + Binder.getCallingPid()
4330 + ", uid=" + Binder.getCallingUid()
4331 + ", (need uid=" + uid + ")"
4332 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004333 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 throw new SecurityException(msg);
4335 }
4336 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004337
Amith Yamasani742a6712011-05-04 14:49:28 -07004338 if (DEBUG_MU)
4339 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4340 + Binder.getOrigCallingUid());
4341 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004342 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 } catch (RemoteException e) {
4345 throw new SecurityException(e);
4346 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004347 }
4348 }
4349
4350 IIntentSender getIntentSenderLocked(int type,
4351 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004352 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4353 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004354 if (DEBUG_MU)
4355 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004356 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004357 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004358 activity = mMainStack.isInStackLocked(token);
4359 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004360 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004362 if (activity.finishing) {
4363 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004365 }
4366
4367 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4368 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4369 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4370 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4371 |PendingIntent.FLAG_UPDATE_CURRENT);
4372
4373 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4374 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004375 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004376 WeakReference<PendingIntentRecord> ref;
4377 ref = mIntentSenderRecords.get(key);
4378 PendingIntentRecord rec = ref != null ? ref.get() : null;
4379 if (rec != null) {
4380 if (!cancelCurrent) {
4381 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004382 if (rec.key.requestIntent != null) {
4383 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4384 }
4385 if (intents != null) {
4386 intents[intents.length-1] = rec.key.requestIntent;
4387 rec.key.allIntents = intents;
4388 rec.key.allResolvedTypes = resolvedTypes;
4389 } else {
4390 rec.key.allIntents = null;
4391 rec.key.allResolvedTypes = null;
4392 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 return rec;
4395 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004396 rec.canceled = true;
4397 mIntentSenderRecords.remove(key);
4398 }
4399 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 return rec;
4401 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004402 rec = new PendingIntentRecord(this, key, callingUid);
4403 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004404 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004405 if (activity.pendingResults == null) {
4406 activity.pendingResults
4407 = new HashSet<WeakReference<PendingIntentRecord>>();
4408 }
4409 activity.pendingResults.add(rec.ref);
4410 }
4411 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 }
4413
4414 public void cancelIntentSender(IIntentSender sender) {
4415 if (!(sender instanceof PendingIntentRecord)) {
4416 return;
4417 }
4418 synchronized(this) {
4419 PendingIntentRecord rec = (PendingIntentRecord)sender;
4420 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004421 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004422 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004423 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 String msg = "Permission Denial: cancelIntentSender() from pid="
4425 + Binder.getCallingPid()
4426 + ", uid=" + Binder.getCallingUid()
4427 + " is not allowed to cancel packges "
4428 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004429 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 throw new SecurityException(msg);
4431 }
4432 } catch (RemoteException e) {
4433 throw new SecurityException(e);
4434 }
4435 cancelIntentSenderLocked(rec, true);
4436 }
4437 }
4438
4439 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4440 rec.canceled = true;
4441 mIntentSenderRecords.remove(rec.key);
4442 if (cleanActivity && rec.key.activity != null) {
4443 rec.key.activity.pendingResults.remove(rec.ref);
4444 }
4445 }
4446
4447 public String getPackageForIntentSender(IIntentSender pendingResult) {
4448 if (!(pendingResult instanceof PendingIntentRecord)) {
4449 return null;
4450 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004451 try {
4452 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4453 return res.key.packageName;
4454 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 }
4456 return null;
4457 }
4458
Christopher Tatec4a07d12012-04-06 14:19:13 -07004459 public int getUidForIntentSender(IIntentSender sender) {
4460 if (sender instanceof PendingIntentRecord) {
4461 try {
4462 PendingIntentRecord res = (PendingIntentRecord)sender;
4463 return res.uid;
4464 } catch (ClassCastException e) {
4465 }
4466 }
4467 return -1;
4468 }
4469
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004470 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4471 if (!(pendingResult instanceof PendingIntentRecord)) {
4472 return false;
4473 }
4474 try {
4475 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4476 if (res.key.allIntents == null) {
4477 return false;
4478 }
4479 for (int i=0; i<res.key.allIntents.length; i++) {
4480 Intent intent = res.key.allIntents[i];
4481 if (intent.getPackage() != null && intent.getComponent() != null) {
4482 return false;
4483 }
4484 }
4485 return true;
4486 } catch (ClassCastException e) {
4487 }
4488 return false;
4489 }
4490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 public void setProcessLimit(int max) {
4492 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4493 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004494 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004495 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004496 mProcessLimitOverride = max;
4497 }
4498 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 }
4500
4501 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004502 synchronized (this) {
4503 return mProcessLimitOverride;
4504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
4506
4507 void foregroundTokenDied(ForegroundToken token) {
4508 synchronized (ActivityManagerService.this) {
4509 synchronized (mPidsSelfLocked) {
4510 ForegroundToken cur
4511 = mForegroundProcesses.get(token.pid);
4512 if (cur != token) {
4513 return;
4514 }
4515 mForegroundProcesses.remove(token.pid);
4516 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4517 if (pr == null) {
4518 return;
4519 }
4520 pr.forcingToForeground = null;
4521 pr.foregroundServices = false;
4522 }
4523 updateOomAdjLocked();
4524 }
4525 }
4526
4527 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4528 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4529 "setProcessForeground()");
4530 synchronized(this) {
4531 boolean changed = false;
4532
4533 synchronized (mPidsSelfLocked) {
4534 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004535 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004536 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 return;
4538 }
4539 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4540 if (oldToken != null) {
4541 oldToken.token.unlinkToDeath(oldToken, 0);
4542 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004543 if (pr != null) {
4544 pr.forcingToForeground = null;
4545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 changed = true;
4547 }
4548 if (isForeground && token != null) {
4549 ForegroundToken newToken = new ForegroundToken() {
4550 public void binderDied() {
4551 foregroundTokenDied(this);
4552 }
4553 };
4554 newToken.pid = pid;
4555 newToken.token = token;
4556 try {
4557 token.linkToDeath(newToken, 0);
4558 mForegroundProcesses.put(pid, newToken);
4559 pr.forcingToForeground = token;
4560 changed = true;
4561 } catch (RemoteException e) {
4562 // If the process died while doing this, we will later
4563 // do the cleanup with the process death link.
4564 }
4565 }
4566 }
4567
4568 if (changed) {
4569 updateOomAdjLocked();
4570 }
4571 }
4572 }
4573
4574 // =========================================================
4575 // PERMISSIONS
4576 // =========================================================
4577
4578 static class PermissionController extends IPermissionController.Stub {
4579 ActivityManagerService mActivityManagerService;
4580 PermissionController(ActivityManagerService activityManagerService) {
4581 mActivityManagerService = activityManagerService;
4582 }
4583
4584 public boolean checkPermission(String permission, int pid, int uid) {
4585 return mActivityManagerService.checkPermission(permission, pid,
4586 uid) == PackageManager.PERMISSION_GRANTED;
4587 }
4588 }
4589
4590 /**
4591 * This can be called with or without the global lock held.
4592 */
4593 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004594 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 // We might be performing an operation on behalf of an indirect binder
4596 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4597 // client identity accordingly before proceeding.
4598 Identity tlsIdentity = sCallerIdentity.get();
4599 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004600 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4602 uid = tlsIdentity.uid;
4603 pid = tlsIdentity.pid;
4604 }
4605
4606 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004607 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 return PackageManager.PERMISSION_GRANTED;
4609 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004610 // Isolated processes don't get any permissions.
4611 if (UserId.isIsolated(uid)) {
4612 return PackageManager.PERMISSION_DENIED;
4613 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004614 // If there is a uid that owns whatever is being accessed, it has
4615 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004616 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004617 return PackageManager.PERMISSION_GRANTED;
4618 }
4619 // If the target is not exported, then nobody else can get to it.
4620 if (!exported) {
4621 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 return PackageManager.PERMISSION_DENIED;
4623 }
4624 if (permission == null) {
4625 return PackageManager.PERMISSION_GRANTED;
4626 }
4627 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004628 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 .checkUidPermission(permission, uid);
4630 } catch (RemoteException e) {
4631 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004632 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 }
4634 return PackageManager.PERMISSION_DENIED;
4635 }
4636
4637 /**
4638 * As the only public entry point for permissions checking, this method
4639 * can enforce the semantic that requesting a check on a null global
4640 * permission is automatically denied. (Internally a null permission
4641 * string is used when calling {@link #checkComponentPermission} in cases
4642 * when only uid-based security is needed.)
4643 *
4644 * This can be called with or without the global lock held.
4645 */
4646 public int checkPermission(String permission, int pid, int uid) {
4647 if (permission == null) {
4648 return PackageManager.PERMISSION_DENIED;
4649 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004650 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 }
4652
4653 /**
4654 * Binder IPC calls go through the public entry point.
4655 * This can be called with or without the global lock held.
4656 */
4657 int checkCallingPermission(String permission) {
4658 return checkPermission(permission,
4659 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004660 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 }
4662
4663 /**
4664 * This can be called with or without the global lock held.
4665 */
4666 void enforceCallingPermission(String permission, String func) {
4667 if (checkCallingPermission(permission)
4668 == PackageManager.PERMISSION_GRANTED) {
4669 return;
4670 }
4671
4672 String msg = "Permission Denial: " + func + " from pid="
4673 + Binder.getCallingPid()
4674 + ", uid=" + Binder.getCallingUid()
4675 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004676 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 throw new SecurityException(msg);
4678 }
4679
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004680 /**
4681 * Determine if UID is holding permissions required to access {@link Uri} in
4682 * the given {@link ProviderInfo}. Final permission checking is always done
4683 * in {@link ContentProvider}.
4684 */
4685 private final boolean checkHoldingPermissionsLocked(
4686 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004687 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4688 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004689
4690 if (pi.applicationInfo.uid == uid) {
4691 return true;
4692 } else if (!pi.exported) {
4693 return false;
4694 }
4695
4696 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4697 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004699 // check if target holds top-level <provider> permissions
4700 if (!readMet && pi.readPermission != null
4701 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4702 readMet = true;
4703 }
4704 if (!writeMet && pi.writePermission != null
4705 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4706 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004708
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004709 // track if unprotected read/write is allowed; any denied
4710 // <path-permission> below removes this ability
4711 boolean allowDefaultRead = pi.readPermission == null;
4712 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004713
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004714 // check if target holds any <path-permission> that match uri
4715 final PathPermission[] pps = pi.pathPermissions;
4716 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004717 final String path = uri.getPath();
4718 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004719 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004720 i--;
4721 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004722 if (pp.match(path)) {
4723 if (!readMet) {
4724 final String pprperm = pp.getReadPermission();
4725 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4726 + pprperm + " for " + pp.getPath()
4727 + ": match=" + pp.match(path)
4728 + " check=" + pm.checkUidPermission(pprperm, uid));
4729 if (pprperm != null) {
4730 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4731 readMet = true;
4732 } else {
4733 allowDefaultRead = false;
4734 }
4735 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004736 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004737 if (!writeMet) {
4738 final String ppwperm = pp.getWritePermission();
4739 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4740 + ppwperm + " for " + pp.getPath()
4741 + ": match=" + pp.match(path)
4742 + " check=" + pm.checkUidPermission(ppwperm, uid));
4743 if (ppwperm != null) {
4744 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4745 writeMet = true;
4746 } else {
4747 allowDefaultWrite = false;
4748 }
4749 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004750 }
4751 }
4752 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004753 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004754
4755 // grant unprotected <provider> read/write, if not blocked by
4756 // <path-permission> above
4757 if (allowDefaultRead) readMet = true;
4758 if (allowDefaultWrite) writeMet = true;
4759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 } catch (RemoteException e) {
4761 return false;
4762 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004763
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004764 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 }
4766
4767 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4768 int modeFlags) {
4769 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004770 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 return true;
4772 }
4773 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4774 if (perms == null) return false;
4775 UriPermission perm = perms.get(uri);
4776 if (perm == null) return false;
4777 return (modeFlags&perm.modeFlags) == modeFlags;
4778 }
4779
4780 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004781 enforceNotIsolatedCaller("checkUriPermission");
4782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 // Another redirected-binder-call permissions check as in
4784 // {@link checkComponentPermission}.
4785 Identity tlsIdentity = sCallerIdentity.get();
4786 if (tlsIdentity != null) {
4787 uid = tlsIdentity.uid;
4788 pid = tlsIdentity.pid;
4789 }
4790
Amith Yamasani742a6712011-05-04 14:49:28 -07004791 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 // Our own process gets to do everything.
4793 if (pid == MY_PID) {
4794 return PackageManager.PERMISSION_GRANTED;
4795 }
4796 synchronized(this) {
4797 return checkUriPermissionLocked(uri, uid, modeFlags)
4798 ? PackageManager.PERMISSION_GRANTED
4799 : PackageManager.PERMISSION_DENIED;
4800 }
4801 }
4802
Dianne Hackborn39792d22010-08-19 18:01:52 -07004803 /**
4804 * Check if the targetPkg can be granted permission to access uri by
4805 * the callingUid using the given modeFlags. Throws a security exception
4806 * if callingUid is not allowed to do this. Returns the uid of the target
4807 * if the URI permission grant should be performed; returns -1 if it is not
4808 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004809 * If you already know the uid of the target, you can supply it in
4810 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004811 */
4812 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004813 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4815 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4816 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004817 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 }
4819
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004820 if (targetPkg != null) {
4821 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4822 "Checking grant " + targetPkg + " permission to " + uri);
4823 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004824
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004825 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826
4827 // If this is not a content: uri, we can't do anything with it.
4828 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004829 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004830 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004831 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 }
4833
4834 String name = uri.getAuthority();
4835 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004836 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4837 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 if (cpr != null) {
4839 pi = cpr.info;
4840 } else {
4841 try {
4842 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004843 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 } catch (RemoteException ex) {
4845 }
4846 }
4847 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004848 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004849 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 }
4851
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004852 int targetUid = lastTargetUid;
4853 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004854 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004855 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004856 if (targetUid < 0) {
4857 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4858 "Can't grant URI permission no uid for: " + targetPkg);
4859 return -1;
4860 }
4861 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004862 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 }
4865
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004866 if (targetUid >= 0) {
4867 // First... does the target actually need this permission?
4868 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4869 // No need to grant the target this permission.
4870 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4871 "Target " + targetPkg + " already has full permission to " + uri);
4872 return -1;
4873 }
4874 } else {
4875 // First... there is no target package, so can anyone access it?
4876 boolean allowed = pi.exported;
4877 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4878 if (pi.readPermission != null) {
4879 allowed = false;
4880 }
4881 }
4882 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4883 if (pi.writePermission != null) {
4884 allowed = false;
4885 }
4886 }
4887 if (allowed) {
4888 return -1;
4889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 }
4891
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004892 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 if (!pi.grantUriPermissions) {
4894 throw new SecurityException("Provider " + pi.packageName
4895 + "/" + pi.name
4896 + " does not allow granting of Uri permissions (uri "
4897 + uri + ")");
4898 }
4899 if (pi.uriPermissionPatterns != null) {
4900 final int N = pi.uriPermissionPatterns.length;
4901 boolean allowed = false;
4902 for (int i=0; i<N; i++) {
4903 if (pi.uriPermissionPatterns[i] != null
4904 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4905 allowed = true;
4906 break;
4907 }
4908 }
4909 if (!allowed) {
4910 throw new SecurityException("Provider " + pi.packageName
4911 + "/" + pi.name
4912 + " does not allow granting of permission to path of Uri "
4913 + uri);
4914 }
4915 }
4916
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004917 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004919 if (callingUid != Process.myUid()) {
4920 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4921 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4922 throw new SecurityException("Uid " + callingUid
4923 + " does not have permission to uri " + uri);
4924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 }
4926 }
4927
Dianne Hackborn39792d22010-08-19 18:01:52 -07004928 return targetUid;
4929 }
4930
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004931 public int checkGrantUriPermission(int callingUid, String targetPkg,
4932 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004933 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004934 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004935 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004936 }
4937 }
4938
Dianne Hackborn39792d22010-08-19 18:01:52 -07004939 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4940 Uri uri, int modeFlags, UriPermissionOwner owner) {
4941 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4942 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4943 if (modeFlags == 0) {
4944 return;
4945 }
4946
4947 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 // to the uri, and the target doesn't. Let's now give this to
4949 // the target.
4950
Joe Onorato8a9b2202010-02-26 18:56:32 -08004951 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004952 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 HashMap<Uri, UriPermission> targetUris
4955 = mGrantedUriPermissions.get(targetUid);
4956 if (targetUris == null) {
4957 targetUris = new HashMap<Uri, UriPermission>();
4958 mGrantedUriPermissions.put(targetUid, targetUris);
4959 }
4960
4961 UriPermission perm = targetUris.get(uri);
4962 if (perm == null) {
4963 perm = new UriPermission(targetUid, uri);
4964 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004968 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004970 } else {
4971 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4972 perm.readOwners.add(owner);
4973 owner.addReadPermission(perm);
4974 }
4975 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4976 perm.writeOwners.add(owner);
4977 owner.addWritePermission(perm);
4978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 }
4980 }
4981
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004982 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4983 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004984 if (targetPkg == null) {
4985 throw new NullPointerException("targetPkg");
4986 }
4987
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004988 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004989 if (targetUid < 0) {
4990 return;
4991 }
4992
4993 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4994 }
4995
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004996 static class NeededUriGrants extends ArrayList<Uri> {
4997 final String targetPkg;
4998 final int targetUid;
4999 final int flags;
5000
5001 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5002 targetPkg = _targetPkg;
5003 targetUid = _targetUid;
5004 flags = _flags;
5005 }
5006 }
5007
Dianne Hackborn39792d22010-08-19 18:01:52 -07005008 /**
5009 * Like checkGrantUriPermissionLocked, but takes an Intent.
5010 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005011 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5012 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005013 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005014 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5015 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005016 + " from " + intent + "; flags=0x"
5017 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5018
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005019 if (targetPkg == null) {
5020 throw new NullPointerException("targetPkg");
5021 }
5022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005024 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 }
5026 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005027 ClipData clip = intent.getClipData();
5028 if (data == null && clip == null) {
5029 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005030 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005031 if (data != null) {
5032 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5033 mode, needed != null ? needed.targetUid : -1);
5034 if (target > 0) {
5035 if (needed == null) {
5036 needed = new NeededUriGrants(targetPkg, target, mode);
5037 }
5038 needed.add(data);
5039 }
5040 }
5041 if (clip != null) {
5042 for (int i=0; i<clip.getItemCount(); i++) {
5043 Uri uri = clip.getItemAt(i).getUri();
5044 if (uri != null) {
5045 int target = -1;
5046 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5047 mode, needed != null ? needed.targetUid : -1);
5048 if (target > 0) {
5049 if (needed == null) {
5050 needed = new NeededUriGrants(targetPkg, target, mode);
5051 }
5052 needed.add(uri);
5053 }
5054 } else {
5055 Intent clipIntent = clip.getItemAt(i).getIntent();
5056 if (clipIntent != null) {
5057 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5058 callingUid, targetPkg, clipIntent, mode, needed);
5059 if (newNeeded != null) {
5060 needed = newNeeded;
5061 }
5062 }
5063 }
5064 }
5065 }
5066
5067 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005068 }
5069
5070 /**
5071 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5072 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005073 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5074 UriPermissionOwner owner) {
5075 if (needed != null) {
5076 for (int i=0; i<needed.size(); i++) {
5077 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5078 needed.get(i), needed.flags, owner);
5079 }
5080 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005081 }
5082
5083 void grantUriPermissionFromIntentLocked(int callingUid,
5084 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005085 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005086 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005087 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 return;
5089 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005090
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005091 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 }
5093
5094 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5095 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005096 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 synchronized(this) {
5098 final ProcessRecord r = getRecordForAppLocked(caller);
5099 if (r == null) {
5100 throw new SecurityException("Unable to find app for caller "
5101 + caller
5102 + " when granting permission to uri " + uri);
5103 }
5104 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005105 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 }
5107 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005108 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 }
5110
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005111 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 null);
5113 }
5114 }
5115
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005116 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5118 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5119 HashMap<Uri, UriPermission> perms
5120 = mGrantedUriPermissions.get(perm.uid);
5121 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005122 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005123 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 perms.remove(perm.uri);
5125 if (perms.size() == 0) {
5126 mGrantedUriPermissions.remove(perm.uid);
5127 }
5128 }
5129 }
5130 }
5131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5133 int modeFlags) {
5134 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5135 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5136 if (modeFlags == 0) {
5137 return;
5138 }
5139
Joe Onorato8a9b2202010-02-26 18:56:32 -08005140 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005141 "Revoking all granted permissions to " + uri);
5142
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005143 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144
5145 final String authority = uri.getAuthority();
5146 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005147 int userId = UserId.getUserId(callingUid);
5148 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 if (cpr != null) {
5150 pi = cpr.info;
5151 } else {
5152 try {
5153 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005154 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 } catch (RemoteException ex) {
5156 }
5157 }
5158 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005159 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 return;
5161 }
5162
5163 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005164 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 // Right now, if you are not the original owner of the permission,
5166 // you are not allowed to revoke it.
5167 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5168 throw new SecurityException("Uid " + callingUid
5169 + " does not have permission to uri " + uri);
5170 //}
5171 }
5172
5173 // Go through all of the permissions and remove any that match.
5174 final List<String> SEGMENTS = uri.getPathSegments();
5175 if (SEGMENTS != null) {
5176 final int NS = SEGMENTS.size();
5177 int N = mGrantedUriPermissions.size();
5178 for (int i=0; i<N; i++) {
5179 HashMap<Uri, UriPermission> perms
5180 = mGrantedUriPermissions.valueAt(i);
5181 Iterator<UriPermission> it = perms.values().iterator();
5182 toploop:
5183 while (it.hasNext()) {
5184 UriPermission perm = it.next();
5185 Uri targetUri = perm.uri;
5186 if (!authority.equals(targetUri.getAuthority())) {
5187 continue;
5188 }
5189 List<String> targetSegments = targetUri.getPathSegments();
5190 if (targetSegments == null) {
5191 continue;
5192 }
5193 if (targetSegments.size() < NS) {
5194 continue;
5195 }
5196 for (int j=0; j<NS; j++) {
5197 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5198 continue toploop;
5199 }
5200 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005201 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005202 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 perm.clearModes(modeFlags);
5204 if (perm.modeFlags == 0) {
5205 it.remove();
5206 }
5207 }
5208 if (perms.size() == 0) {
5209 mGrantedUriPermissions.remove(
5210 mGrantedUriPermissions.keyAt(i));
5211 N--;
5212 i--;
5213 }
5214 }
5215 }
5216 }
5217
5218 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5219 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005220 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005221 synchronized(this) {
5222 final ProcessRecord r = getRecordForAppLocked(caller);
5223 if (r == null) {
5224 throw new SecurityException("Unable to find app for caller "
5225 + caller
5226 + " when revoking permission to uri " + uri);
5227 }
5228 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005229 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 return;
5231 }
5232
5233 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5234 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5235 if (modeFlags == 0) {
5236 return;
5237 }
5238
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005239 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240
5241 final String authority = uri.getAuthority();
5242 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005243 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 if (cpr != null) {
5245 pi = cpr.info;
5246 } else {
5247 try {
5248 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005249 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 } catch (RemoteException ex) {
5251 }
5252 }
5253 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005254 Slog.w(TAG, "No content provider found for permission revoke: "
5255 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 return;
5257 }
5258
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005259 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 }
5261 }
5262
Dianne Hackborn7e269642010-08-25 19:50:20 -07005263 @Override
5264 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005265 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005266 synchronized(this) {
5267 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5268 return owner.getExternalTokenLocked();
5269 }
5270 }
5271
5272 @Override
5273 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5274 Uri uri, int modeFlags) {
5275 synchronized(this) {
5276 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5277 if (owner == null) {
5278 throw new IllegalArgumentException("Unknown owner: " + token);
5279 }
5280 if (fromUid != Binder.getCallingUid()) {
5281 if (Binder.getCallingUid() != Process.myUid()) {
5282 // Only system code can grant URI permissions on behalf
5283 // of other users.
5284 throw new SecurityException("nice try");
5285 }
5286 }
5287 if (targetPkg == null) {
5288 throw new IllegalArgumentException("null target");
5289 }
5290 if (uri == null) {
5291 throw new IllegalArgumentException("null uri");
5292 }
5293
5294 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5295 }
5296 }
5297
5298 @Override
5299 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5300 synchronized(this) {
5301 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5302 if (owner == null) {
5303 throw new IllegalArgumentException("Unknown owner: " + token);
5304 }
5305
5306 if (uri == null) {
5307 owner.removeUriPermissionsLocked(mode);
5308 } else {
5309 owner.removeUriPermissionLocked(uri, mode);
5310 }
5311 }
5312 }
5313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5315 synchronized (this) {
5316 ProcessRecord app =
5317 who != null ? getRecordForAppLocked(who) : null;
5318 if (app == null) return;
5319
5320 Message msg = Message.obtain();
5321 msg.what = WAIT_FOR_DEBUGGER_MSG;
5322 msg.obj = app;
5323 msg.arg1 = waiting ? 1 : 0;
5324 mHandler.sendMessage(msg);
5325 }
5326 }
5327
5328 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005329 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5330 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005332 outInfo.threshold = homeAppMem;
5333 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5334 outInfo.hiddenAppThreshold = hiddenAppMem;
5335 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005336 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005337 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5338 ProcessList.VISIBLE_APP_ADJ);
5339 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5340 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 }
5342
5343 // =========================================================
5344 // TASK MANAGEMENT
5345 // =========================================================
5346
5347 public List getTasks(int maxNum, int flags,
5348 IThumbnailReceiver receiver) {
5349 ArrayList list = new ArrayList();
5350
5351 PendingThumbnailsRecord pending = null;
5352 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005353 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354
5355 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005356 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5358 + ", receiver=" + receiver);
5359
5360 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5361 != PackageManager.PERMISSION_GRANTED) {
5362 if (receiver != null) {
5363 // If the caller wants to wait for pending thumbnails,
5364 // it ain't gonna get them.
5365 try {
5366 receiver.finished();
5367 } catch (RemoteException ex) {
5368 }
5369 }
5370 String msg = "Permission Denial: getTasks() from pid="
5371 + Binder.getCallingPid()
5372 + ", uid=" + Binder.getCallingUid()
5373 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005374 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005375 throw new SecurityException(msg);
5376 }
5377
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005378 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005379 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005380 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005381 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 TaskRecord curTask = null;
5383 int numActivities = 0;
5384 int numRunning = 0;
5385 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005386 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005388 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389
5390 // Initialize state for next task if needed.
5391 if (top == null ||
5392 (top.state == ActivityState.INITIALIZING
5393 && top.task == r.task)) {
5394 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 curTask = r.task;
5396 numActivities = numRunning = 0;
5397 }
5398
5399 // Add 'r' into the current task.
5400 numActivities++;
5401 if (r.app != null && r.app.thread != null) {
5402 numRunning++;
5403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404
Joe Onorato8a9b2202010-02-26 18:56:32 -08005405 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005406 TAG, r.intent.getComponent().flattenToShortString()
5407 + ": task=" + r.task);
5408
5409 // If the next one is a different task, generate a new
5410 // TaskInfo entry for what we have.
5411 if (next == null || next.task != curTask) {
5412 ActivityManager.RunningTaskInfo ci
5413 = new ActivityManager.RunningTaskInfo();
5414 ci.id = curTask.taskId;
5415 ci.baseActivity = r.intent.getComponent();
5416 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005417 if (top.thumbHolder != null) {
5418 ci.description = top.thumbHolder.lastDescription;
5419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 ci.numActivities = numActivities;
5421 ci.numRunning = numRunning;
5422 //System.out.println(
5423 // "#" + maxNum + ": " + " descr=" + ci.description);
5424 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005425 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 TAG, "State=" + top.state + "Idle=" + top.idle
5427 + " app=" + top.app
5428 + " thr=" + (top.app != null ? top.app.thread : null));
5429 if (top.state == ActivityState.RESUMED
5430 || top.state == ActivityState.PAUSING) {
5431 if (top.idle && top.app != null
5432 && top.app.thread != null) {
5433 topRecord = top;
5434 topThumbnail = top.app.thread;
5435 } else {
5436 top.thumbnailNeeded = true;
5437 }
5438 }
5439 if (pending == null) {
5440 pending = new PendingThumbnailsRecord(receiver);
5441 }
5442 pending.pendingRecords.add(top);
5443 }
5444 list.add(ci);
5445 maxNum--;
5446 top = null;
5447 }
5448 }
5449
5450 if (pending != null) {
5451 mPendingThumbnails.add(pending);
5452 }
5453 }
5454
Joe Onorato8a9b2202010-02-26 18:56:32 -08005455 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456
5457 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005458 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005460 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005462 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005463 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 }
5465 }
5466
5467 if (pending == null && receiver != null) {
5468 // In this case all thumbnails were available and the client
5469 // is being asked to be told when the remaining ones come in...
5470 // which is unusually, since the top-most currently running
5471 // activity should never have a canned thumbnail! Oh well.
5472 try {
5473 receiver.finished();
5474 } catch (RemoteException ex) {
5475 }
5476 }
5477
5478 return list;
5479 }
5480
5481 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5482 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005483 final int callingUid = Binder.getCallingUid();
5484 // If it's the system uid asking, then use the current user id.
5485 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5486 // require the entire list.
5487 final int callingUserId = callingUid == Process.SYSTEM_UID
5488 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 synchronized (this) {
5490 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5491 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005492 final boolean detailed = checkCallingPermission(
5493 android.Manifest.permission.GET_DETAILED_TASKS)
5494 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005496 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 final int N = mRecentTasks.size();
5499 ArrayList<ActivityManager.RecentTaskInfo> res
5500 = new ArrayList<ActivityManager.RecentTaskInfo>(
5501 maxNum < N ? maxNum : N);
5502 for (int i=0; i<N && maxNum > 0; i++) {
5503 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005504 // Only add calling user's recent tasks
5505 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005506 // Return the entry if desired by the caller. We always return
5507 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005508 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005509 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5510 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005511
Dianne Hackborn905577f2011-09-07 18:31:28 -07005512 if (i == 0
5513 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 || (tr.intent == null)
5515 || ((tr.intent.getFlags()
5516 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5517 ActivityManager.RecentTaskInfo rti
5518 = new ActivityManager.RecentTaskInfo();
5519 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005520 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 rti.baseIntent = new Intent(
5522 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005523 if (!detailed) {
5524 rti.baseIntent.replaceExtras((Bundle)null);
5525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005527 rti.description = tr.lastDescription;
5528
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005529 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5530 // Check whether this activity is currently available.
5531 try {
5532 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005533 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5534 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005535 continue;
5536 }
5537 } else if (rti.baseIntent != null) {
5538 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005539 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005540 continue;
5541 }
5542 }
5543 } catch (RemoteException e) {
5544 // Will never happen.
5545 }
5546 }
5547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 res.add(rti);
5549 maxNum--;
5550 }
5551 }
5552 return res;
5553 }
5554 }
5555
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005556 private TaskRecord taskForIdLocked(int id) {
5557 final int N = mRecentTasks.size();
5558 for (int i=0; i<N; i++) {
5559 TaskRecord tr = mRecentTasks.get(i);
5560 if (tr.taskId == id) {
5561 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005562 }
5563 }
5564 return null;
5565 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005566
5567 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5568 synchronized (this) {
5569 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5570 "getTaskThumbnails()");
5571 TaskRecord tr = taskForIdLocked(id);
5572 if (tr != null) {
5573 return mMainStack.getTaskThumbnailsLocked(tr);
5574 }
5575 }
5576 return null;
5577 }
5578
5579 public boolean removeSubTask(int taskId, int subTaskIndex) {
5580 synchronized (this) {
5581 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5582 "removeSubTask()");
5583 long ident = Binder.clearCallingIdentity();
5584 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005585 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5586 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005587 } finally {
5588 Binder.restoreCallingIdentity(ident);
5589 }
5590 }
5591 }
5592
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005593 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5594 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005595 Intent baseIntent = new Intent(
5596 tr.intent != null ? tr.intent : tr.affinityIntent);
5597 ComponentName component = baseIntent.getComponent();
5598 if (component == null) {
5599 Slog.w(TAG, "Now component for base intent of task: " + tr);
5600 return;
5601 }
5602
5603 // Find any running services associated with this app.
5604 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005605 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005606 if (sr.packageName.equals(component.getPackageName())) {
5607 services.add(sr);
5608 }
5609 }
5610
5611 // Take care of any running services associated with the app.
5612 for (int i=0; i<services.size(); i++) {
5613 ServiceRecord sr = services.get(i);
5614 if (sr.startRequested) {
5615 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005616 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005617 stopServiceLocked(sr);
5618 } else {
5619 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005620 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005621 if (sr.app != null && sr.app.thread != null) {
5622 sendServiceArgsLocked(sr, false);
5623 }
5624 }
5625 }
5626 }
5627
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005628 if (killProcesses) {
5629 // Find any running processes associated with this app.
5630 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5631 SparseArray<ProcessRecord> appProcs
5632 = mProcessNames.getMap().get(component.getPackageName());
5633 if (appProcs != null) {
5634 for (int i=0; i<appProcs.size(); i++) {
5635 procs.add(appProcs.valueAt(i));
5636 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005637 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005638
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005639 // Kill the running processes.
5640 for (int i=0; i<procs.size(); i++) {
5641 ProcessRecord pr = procs.get(i);
5642 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5643 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5644 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5645 pr.processName, pr.setAdj, "remove task");
5646 Process.killProcessQuiet(pr.pid);
5647 } else {
5648 pr.waitingToKill = "remove task";
5649 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005650 }
5651 }
5652 }
5653
5654 public boolean removeTask(int taskId, int flags) {
5655 synchronized (this) {
5656 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5657 "removeTask()");
5658 long ident = Binder.clearCallingIdentity();
5659 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005660 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5661 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005662 if (r != null) {
5663 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005664 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005665 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005666 } else {
5667 TaskRecord tr = null;
5668 int i=0;
5669 while (i < mRecentTasks.size()) {
5670 TaskRecord t = mRecentTasks.get(i);
5671 if (t.taskId == taskId) {
5672 tr = t;
5673 break;
5674 }
5675 i++;
5676 }
5677 if (tr != null) {
5678 if (tr.numActivities <= 0) {
5679 // Caller is just removing a recent task that is
5680 // not actively running. That is easy!
5681 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005682 cleanUpRemovedTaskLocked(tr, flags);
5683 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005684 } else {
5685 Slog.w(TAG, "removeTask: task " + taskId
5686 + " does not have activities to remove, "
5687 + " but numActivities=" + tr.numActivities
5688 + ": " + tr);
5689 }
5690 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005691 }
5692 } finally {
5693 Binder.restoreCallingIdentity(ident);
5694 }
5695 }
5696 return false;
5697 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5700 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005701 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 TaskRecord jt = startTask;
5703
5704 // First look backwards
5705 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005706 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 if (r.task != jt) {
5708 jt = r.task;
5709 if (affinity.equals(jt.affinity)) {
5710 return j;
5711 }
5712 }
5713 }
5714
5715 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005716 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 jt = startTask;
5718 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005719 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 if (r.task != jt) {
5721 if (affinity.equals(jt.affinity)) {
5722 return j;
5723 }
5724 jt = r.task;
5725 }
5726 }
5727
5728 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005729 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 return N-1;
5731 }
5732
5733 return -1;
5734 }
5735
5736 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005737 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005739 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5741 "moveTaskToFront()");
5742
5743 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005744 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5745 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005746 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005747 return;
5748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 final long origId = Binder.clearCallingIdentity();
5750 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005751 TaskRecord tr = taskForIdLocked(task);
5752 if (tr != null) {
5753 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5754 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005756 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5757 // Caller wants the home activity moved with it. To accomplish this,
5758 // we'll just move the home task to the top first.
5759 mMainStack.moveHomeToFrontLocked();
5760 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005761 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005762 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005764 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5765 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005767 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5768 mMainStack.mUserLeaving = true;
5769 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005770 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5771 // Caller wants the home activity moved with it. To accomplish this,
5772 // we'll just move the home task to the top first.
5773 mMainStack.moveHomeToFrontLocked();
5774 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005775 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 return;
5777 }
5778 }
5779 } finally {
5780 Binder.restoreCallingIdentity(origId);
5781 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005782 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 }
5784 }
5785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 public void moveTaskToBack(int task) {
5787 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5788 "moveTaskToBack()");
5789
5790 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005791 if (mMainStack.mResumedActivity != null
5792 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005793 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5794 Binder.getCallingUid(), "Task to back")) {
5795 return;
5796 }
5797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005799 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 Binder.restoreCallingIdentity(origId);
5801 }
5802 }
5803
5804 /**
5805 * Moves an activity, and all of the other activities within the same task, to the bottom
5806 * of the history stack. The activity's order within the task is unchanged.
5807 *
5808 * @param token A reference to the activity we wish to move
5809 * @param nonRoot If false then this only works if the activity is the root
5810 * of a task; if true it will work for any activity in a task.
5811 * @return Returns true if the move completed, false if not.
5812 */
5813 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005814 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 synchronized(this) {
5816 final long origId = Binder.clearCallingIdentity();
5817 int taskId = getTaskForActivityLocked(token, !nonRoot);
5818 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005819 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 }
5821 Binder.restoreCallingIdentity(origId);
5822 }
5823 return false;
5824 }
5825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 public void moveTaskBackwards(int task) {
5827 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5828 "moveTaskBackwards()");
5829
5830 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005831 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5832 Binder.getCallingUid(), "Task backwards")) {
5833 return;
5834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 final long origId = Binder.clearCallingIdentity();
5836 moveTaskBackwardsLocked(task);
5837 Binder.restoreCallingIdentity(origId);
5838 }
5839 }
5840
5841 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005842 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 }
5844
5845 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5846 synchronized(this) {
5847 return getTaskForActivityLocked(token, onlyRoot);
5848 }
5849 }
5850
5851 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005852 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 TaskRecord lastTask = null;
5854 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005855 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005856 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 if (!onlyRoot || lastTask != r.task) {
5858 return r.task.taskId;
5859 }
5860 return -1;
5861 }
5862 lastTask = r.task;
5863 }
5864
5865 return -1;
5866 }
5867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 // =========================================================
5869 // THUMBNAILS
5870 // =========================================================
5871
5872 public void reportThumbnail(IBinder token,
5873 Bitmap thumbnail, CharSequence description) {
5874 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5875 final long origId = Binder.clearCallingIdentity();
5876 sendPendingThumbnail(null, token, thumbnail, description, true);
5877 Binder.restoreCallingIdentity(origId);
5878 }
5879
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005880 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 Bitmap thumbnail, CharSequence description, boolean always) {
5882 TaskRecord task = null;
5883 ArrayList receivers = null;
5884
5885 //System.out.println("Send pending thumbnail: " + r);
5886
5887 synchronized(this) {
5888 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005889 r = mMainStack.isInStackLocked(token);
5890 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 return;
5892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005894 if (thumbnail == null && r.thumbHolder != null) {
5895 thumbnail = r.thumbHolder.lastThumbnail;
5896 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 }
5898 if (thumbnail == null && !always) {
5899 // If there is no thumbnail, and this entry is not actually
5900 // going away, then abort for now and pick up the next
5901 // thumbnail we get.
5902 return;
5903 }
5904 task = r.task;
5905
5906 int N = mPendingThumbnails.size();
5907 int i=0;
5908 while (i<N) {
5909 PendingThumbnailsRecord pr =
5910 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5911 //System.out.println("Looking in " + pr.pendingRecords);
5912 if (pr.pendingRecords.remove(r)) {
5913 if (receivers == null) {
5914 receivers = new ArrayList();
5915 }
5916 receivers.add(pr);
5917 if (pr.pendingRecords.size() == 0) {
5918 pr.finished = true;
5919 mPendingThumbnails.remove(i);
5920 N--;
5921 continue;
5922 }
5923 }
5924 i++;
5925 }
5926 }
5927
5928 if (receivers != null) {
5929 final int N = receivers.size();
5930 for (int i=0; i<N; i++) {
5931 try {
5932 PendingThumbnailsRecord pr =
5933 (PendingThumbnailsRecord)receivers.get(i);
5934 pr.receiver.newThumbnail(
5935 task != null ? task.taskId : -1, thumbnail, description);
5936 if (pr.finished) {
5937 pr.receiver.finished();
5938 }
5939 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005940 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941 }
5942 }
5943 }
5944 }
5945
5946 // =========================================================
5947 // CONTENT PROVIDERS
5948 // =========================================================
5949
Jeff Brown10e89712011-07-08 18:52:57 -07005950 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5951 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005953 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005954 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005955 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 } catch (RemoteException ex) {
5957 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005958 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005959 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5960 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 if (providers != null) {
5962 final int N = providers.size();
5963 for (int i=0; i<N; i++) {
5964 ProviderInfo cpi =
5965 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005966
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005967 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005968 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005970 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005971 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005973 if (DEBUG_MU)
5974 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 app.pubProviders.put(cpi.name, cpr);
5976 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005977 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 }
5979 }
5980 return providers;
5981 }
5982
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005983 /**
5984 * Check if {@link ProcessRecord} has a possible chance at accessing the
5985 * given {@link ProviderInfo}. Final permission checking is always done
5986 * in {@link ContentProvider}.
5987 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005989 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005990 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005991 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005993 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005994 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 return null;
5996 }
5997 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005998 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 == PackageManager.PERMISSION_GRANTED) {
6000 return null;
6001 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006002
6003 PathPermission[] pps = cpi.pathPermissions;
6004 if (pps != null) {
6005 int i = pps.length;
6006 while (i > 0) {
6007 i--;
6008 PathPermission pp = pps[i];
6009 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006010 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006011 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006012 return null;
6013 }
6014 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006015 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006016 == PackageManager.PERMISSION_GRANTED) {
6017 return null;
6018 }
6019 }
6020 }
6021
Dianne Hackbornb424b632010-08-18 15:59:05 -07006022 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6023 if (perms != null) {
6024 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6025 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6026 return null;
6027 }
6028 }
6029 }
6030
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006031 String msg;
6032 if (!cpi.exported) {
6033 msg = "Permission Denial: opening provider " + cpi.name
6034 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6035 + ", uid=" + callingUid + ") that is not exported from uid "
6036 + cpi.applicationInfo.uid;
6037 } else {
6038 msg = "Permission Denial: opening provider " + cpi.name
6039 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6040 + ", uid=" + callingUid + ") requires "
6041 + cpi.readPermission + " or " + cpi.writePermission;
6042 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006043 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 return msg;
6045 }
6046
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006047 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6048 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006049 if (r != null) {
6050 Integer cnt = r.conProviders.get(cpr);
6051 if (DEBUG_PROVIDER) Slog.v(TAG,
6052 "Adding provider requested by "
6053 + r.processName + " from process "
6054 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6055 + " cnt=" + (cnt == null ? 1 : cnt));
6056 if (cnt == null) {
6057 cpr.clients.add(r);
6058 r.conProviders.put(cpr, new Integer(1));
6059 return true;
6060 } else {
6061 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6062 }
6063 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006064 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006065 }
6066 return false;
6067 }
6068
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006069 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6070 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006071 if (r != null) {
6072 Integer cnt = r.conProviders.get(cpr);
6073 if (DEBUG_PROVIDER) Slog.v(TAG,
6074 "Removing provider requested by "
6075 + r.processName + " from process "
6076 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6077 + " cnt=" + cnt);
6078 if (cnt == null || cnt.intValue() <= 1) {
6079 cpr.clients.remove(r);
6080 r.conProviders.remove(cpr);
6081 return true;
6082 } else {
6083 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6084 }
6085 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006086 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006087 }
6088 return false;
6089 }
6090
Amith Yamasani742a6712011-05-04 14:49:28 -07006091 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006092 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 ContentProviderRecord cpr;
6094 ProviderInfo cpi = null;
6095
6096 synchronized(this) {
6097 ProcessRecord r = null;
6098 if (caller != null) {
6099 r = getRecordForAppLocked(caller);
6100 if (r == null) {
6101 throw new SecurityException(
6102 "Unable to find app for caller " + caller
6103 + " (pid=" + Binder.getCallingPid()
6104 + ") when getting content provider " + name);
6105 }
6106 }
6107
6108 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006109 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006110 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006111 boolean providerRunning = cpr != null;
6112 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006114 String msg;
6115 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6116 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 }
6118
6119 if (r != null && cpr.canRunHere(r)) {
6120 // This provider has been published or is in the process
6121 // of being published... but it is also allowed to run
6122 // in the caller's process, so don't make a connection
6123 // and just let the caller instantiate its own instance.
6124 if (cpr.provider != null) {
6125 // don't give caller the provider object, it needs
6126 // to make its own.
6127 cpr = new ContentProviderRecord(cpr);
6128 }
6129 return cpr;
6130 }
6131
6132 final long origId = Binder.clearCallingIdentity();
6133
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006134 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006136 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006137 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006138 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006139 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006140 // make sure to count it as being accessed and thus
6141 // back up on the LRU list. This is good because
6142 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006143 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006144 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006145 }
6146
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006147 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006148 if (false) {
6149 if (cpr.name.flattenToShortString().equals(
6150 "com.android.providers.calendar/.CalendarProvider2")) {
6151 Slog.v(TAG, "****************** KILLING "
6152 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006153 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006154 }
6155 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006156 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006157 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6158 // NOTE: there is still a race here where a signal could be
6159 // pending on the process even though we managed to update its
6160 // adj level. Not sure what to do about this, but at least
6161 // the race is now smaller.
6162 if (!success) {
6163 // Uh oh... it looks like the provider's process
6164 // has been killed on us. We need to wait for a new
6165 // process to be started, and make sure its death
6166 // doesn't kill our process.
6167 Slog.i(TAG,
6168 "Existing provider " + cpr.name.flattenToShortString()
6169 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006170 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006171 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006172 if (!lastRef) {
6173 // This wasn't the last ref our process had on
6174 // the provider... we have now been killed, bail.
6175 return null;
6176 }
6177 providerRunning = false;
6178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 }
6180
6181 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006184 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006186 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006187 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006188 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 } catch (RemoteException ex) {
6190 }
6191 if (cpi == null) {
6192 return null;
6193 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006194 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6195 userId = 0;
6196 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006197 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006198
Dianne Hackbornb424b632010-08-18 15:59:05 -07006199 String msg;
6200 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6201 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 }
6203
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006204 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006205 && !cpi.processName.equals("system")) {
6206 // If this content provider does not run in the system
6207 // process, and the system is not yet ready to run other
6208 // processes, then fail fast instead of hanging.
6209 throw new IllegalArgumentException(
6210 "Attempt to launch content provider before system ready");
6211 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006212
6213 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006214 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 final boolean firstClass = cpr == null;
6216 if (firstClass) {
6217 try {
6218 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006219 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 getApplicationInfo(
6221 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006222 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006224 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 + cpi.name);
6226 return null;
6227 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006228 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006229 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 } catch (RemoteException ex) {
6231 // pm is in same process, this will never happen.
6232 }
6233 }
6234
6235 if (r != null && cpr.canRunHere(r)) {
6236 // If this is a multiprocess provider, then just return its
6237 // info and allow the caller to instantiate it. Only do
6238 // this if the provider is the same user as the caller's
6239 // process, or can run as root (so can be in any process).
6240 return cpr;
6241 }
6242
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006243 if (DEBUG_PROVIDER) {
6244 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006245 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006246 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 }
6248
6249 // This is single process, and our app is now connecting to it.
6250 // See if we are already in the process of launching this
6251 // provider.
6252 final int N = mLaunchingProviders.size();
6253 int i;
6254 for (i=0; i<N; i++) {
6255 if (mLaunchingProviders.get(i) == cpr) {
6256 break;
6257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 }
6259
6260 // If the provider is not already being launched, then get it
6261 // started.
6262 if (i >= N) {
6263 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006264
6265 try {
6266 // Content provider is now in use, its package can't be stopped.
6267 try {
6268 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006269 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006270 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006271 } catch (IllegalArgumentException e) {
6272 Slog.w(TAG, "Failed trying to unstop package "
6273 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006274 }
6275
6276 ProcessRecord proc = startProcessLocked(cpi.processName,
6277 cpr.appInfo, false, 0, "content provider",
6278 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006279 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006280 if (proc == null) {
6281 Slog.w(TAG, "Unable to launch app "
6282 + cpi.applicationInfo.packageName + "/"
6283 + cpi.applicationInfo.uid + " for provider "
6284 + name + ": process is bad");
6285 return null;
6286 }
6287 cpr.launchingApp = proc;
6288 mLaunchingProviders.add(cpr);
6289 } finally {
6290 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
6293
6294 // Make sure the provider is published (the same provider class
6295 // may be published under multiple names).
6296 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006297 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006299
Amith Yamasani742a6712011-05-04 14:49:28 -07006300 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006301 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 }
6303 }
6304
6305 // Wait for the provider to be published...
6306 synchronized (cpr) {
6307 while (cpr.provider == null) {
6308 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006309 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 + cpi.applicationInfo.packageName + "/"
6311 + cpi.applicationInfo.uid + " for provider "
6312 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006313 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 cpi.applicationInfo.packageName,
6315 cpi.applicationInfo.uid, name);
6316 return null;
6317 }
6318 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006319 if (DEBUG_MU) {
6320 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6321 + cpr.launchingApp);
6322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 cpr.wait();
6324 } catch (InterruptedException ex) {
6325 }
6326 }
6327 }
6328 return cpr;
6329 }
6330
6331 public final ContentProviderHolder getContentProvider(
6332 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006333 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 if (caller == null) {
6335 String msg = "null IApplicationThread when getting content provider "
6336 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006337 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 throw new SecurityException(msg);
6339 }
6340
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006341 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 }
6343
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006344 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6345 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6346 "Do not have permission in call getContentProviderExternal()");
6347 return getContentProviderExternalUnchecked(name, token);
6348 }
6349
6350 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6351 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 }
6353
6354 /**
6355 * Drop a content provider from a ProcessRecord's bookkeeping
6356 * @param cpr
6357 */
6358 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006359 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006361 int userId = UserId.getUserId(Binder.getCallingUid());
6362 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006364 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006365 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006366 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 return;
6368 }
6369 final ProcessRecord r = getRecordForAppLocked(caller);
6370 if (r == null) {
6371 throw new SecurityException(
6372 "Unable to find app for caller " + caller +
6373 " when removing content provider " + name);
6374 }
6375 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006376 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006377 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6378 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6379 + r.info.processName + " from process "
6380 + localCpr.appInfo.processName);
6381 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006383 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006384 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 return;
6386 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006387 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006388 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 }
6392 }
6393
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006394 public void removeContentProviderExternal(String name, IBinder token) {
6395 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6396 "Do not have permission in call removeContentProviderExternal()");
6397 removeContentProviderExternalUnchecked(name, token);
6398 }
6399
6400 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006402 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6403 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 if(cpr == null) {
6405 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006406 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 return;
6408 }
6409
6410 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006411 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006412 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6413 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006414 if (localCpr.hasExternalProcessHandles()) {
6415 if (localCpr.removeExternalProcessHandleLocked(token)) {
6416 updateOomAdjLocked();
6417 } else {
6418 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6419 + " with no external reference for token: "
6420 + token + ".");
6421 }
6422 } else {
6423 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6424 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 }
6427 }
6428
6429 public final void publishContentProviders(IApplicationThread caller,
6430 List<ContentProviderHolder> providers) {
6431 if (providers == null) {
6432 return;
6433 }
6434
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006435 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 synchronized(this) {
6437 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006438 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006439 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 if (r == null) {
6441 throw new SecurityException(
6442 "Unable to find app for caller " + caller
6443 + " (pid=" + Binder.getCallingPid()
6444 + ") when publishing content providers");
6445 }
6446
6447 final long origId = Binder.clearCallingIdentity();
6448
6449 final int N = providers.size();
6450 for (int i=0; i<N; i++) {
6451 ContentProviderHolder src = providers.get(i);
6452 if (src == null || src.info == null || src.provider == null) {
6453 continue;
6454 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006455 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006456 if (DEBUG_MU)
6457 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006459 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006460 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 String names[] = dst.info.authority.split(";");
6462 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006463 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 }
6465
6466 int NL = mLaunchingProviders.size();
6467 int j;
6468 for (j=0; j<NL; j++) {
6469 if (mLaunchingProviders.get(j) == dst) {
6470 mLaunchingProviders.remove(j);
6471 j--;
6472 NL--;
6473 }
6474 }
6475 synchronized (dst) {
6476 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006477 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 dst.notifyAll();
6479 }
6480 updateOomAdjLocked(r);
6481 }
6482 }
6483
6484 Binder.restoreCallingIdentity(origId);
6485 }
6486 }
6487
6488 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006489 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006490 synchronized (mSelf) {
6491 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6492 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006493 if (providers != null) {
6494 for (int i=providers.size()-1; i>=0; i--) {
6495 ProviderInfo pi = (ProviderInfo)providers.get(i);
6496 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6497 Slog.w(TAG, "Not installing system proc provider " + pi.name
6498 + ": not system .apk");
6499 providers.remove(i);
6500 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006501 }
6502 }
6503 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006504 if (providers != null) {
6505 mSystemThread.installSystemProviders(providers);
6506 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006507
6508 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006509
6510 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 }
6512
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006513 /**
6514 * Allows app to retrieve the MIME type of a URI without having permission
6515 * to access its content provider.
6516 *
6517 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6518 *
6519 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6520 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6521 */
6522 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006523 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006524 final String name = uri.getAuthority();
6525 final long ident = Binder.clearCallingIdentity();
6526 ContentProviderHolder holder = null;
6527
6528 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006529 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006530 if (holder != null) {
6531 return holder.provider.getType(uri);
6532 }
6533 } catch (RemoteException e) {
6534 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6535 return null;
6536 } finally {
6537 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006538 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006539 }
6540 Binder.restoreCallingIdentity(ident);
6541 }
6542
6543 return null;
6544 }
6545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 // =========================================================
6547 // GLOBAL MANAGEMENT
6548 // =========================================================
6549
6550 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006551 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 String proc = customProcess != null ? customProcess : info.processName;
6553 BatteryStatsImpl.Uid.Proc ps = null;
6554 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006555 int uid = info.uid;
6556 if (isolated) {
6557 int userId = UserId.getUserId(uid);
6558 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6559 uid = 0;
6560 while (true) {
6561 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6562 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6563 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6564 }
6565 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6566 mNextIsolatedProcessUid++;
6567 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6568 // No process for this uid, use it.
6569 break;
6570 }
6571 stepsLeft--;
6572 if (stepsLeft <= 0) {
6573 return null;
6574 }
6575 }
6576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 synchronized (stats) {
6578 ps = stats.getProcessStatsLocked(info.uid, proc);
6579 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006580 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 }
6582
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006583 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6584 ProcessRecord app;
6585 if (!isolated) {
6586 app = getProcessRecordLocked(info.processName, info.uid);
6587 } else {
6588 app = null;
6589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590
6591 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006592 app = newProcessRecordLocked(null, info, null, isolated);
6593 mProcessNames.put(info.processName, app.uid, app);
6594 if (isolated) {
6595 mIsolatedProcesses.put(app.uid, app);
6596 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006597 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 }
6599
Dianne Hackborne7f97212011-02-24 14:40:20 -08006600 // This package really, really can not be stopped.
6601 try {
6602 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006603 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006604 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006605 } catch (IllegalArgumentException e) {
6606 Slog.w(TAG, "Failed trying to unstop package "
6607 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006608 }
6609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6611 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6612 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006613 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 }
6615 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6616 mPersistentStartingProcesses.add(app);
6617 startProcessLocked(app, "added application", app.processName);
6618 }
6619
6620 return app;
6621 }
6622
6623 public void unhandledBack() {
6624 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6625 "unhandledBack()");
6626
6627 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006628 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006629 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 TAG, "Performing unhandledBack(): stack size = " + count);
6631 if (count > 1) {
6632 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006633 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6635 Binder.restoreCallingIdentity(origId);
6636 }
6637 }
6638 }
6639
6640 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006641 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006643 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 ParcelFileDescriptor pfd = null;
6645 if (cph != null) {
6646 // We record the binder invoker's uid in thread-local storage before
6647 // going to the content provider to open the file. Later, in the code
6648 // that handles all permissions checks, we look for this uid and use
6649 // that rather than the Activity Manager's own uid. The effect is that
6650 // we do the check against the caller's permissions even though it looks
6651 // to the content provider like the Activity Manager itself is making
6652 // the request.
6653 sCallerIdentity.set(new Identity(
6654 Binder.getCallingPid(), Binder.getCallingUid()));
6655 try {
6656 pfd = cph.provider.openFile(uri, "r");
6657 } catch (FileNotFoundException e) {
6658 // do nothing; pfd will be returned null
6659 } finally {
6660 // Ensure that whatever happens, we clean up the identity state
6661 sCallerIdentity.remove();
6662 }
6663
6664 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006665 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006667 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 }
6669 return pfd;
6670 }
6671
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006672 // Actually is sleeping or shutting down or whatever else in the future
6673 // is an inactive state.
6674 public boolean isSleeping() {
6675 return mSleeping || mShuttingDown;
6676 }
6677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006678 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006679 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6680 != PackageManager.PERMISSION_GRANTED) {
6681 throw new SecurityException("Requires permission "
6682 + android.Manifest.permission.DEVICE_POWER);
6683 }
6684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006686 mWentToSleep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 mWindowManager.setEventDispatching(false);
6688
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006689 if (!mSleeping) {
6690 mSleeping = true;
6691 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006692
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006693 // Initialize the wake times of all processes.
6694 checkExcessivePowerUsageLocked(false);
6695 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6696 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6697 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 }
6700 }
6701
Dianne Hackborn55280a92009-05-07 15:53:46 -07006702 public boolean shutdown(int timeout) {
6703 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6704 != PackageManager.PERMISSION_GRANTED) {
6705 throw new SecurityException("Requires permission "
6706 + android.Manifest.permission.SHUTDOWN);
6707 }
6708
6709 boolean timedout = false;
6710
6711 synchronized(this) {
6712 mShuttingDown = true;
6713 mWindowManager.setEventDispatching(false);
6714
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006715 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006716 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006717 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006718 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006719 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006720 long delay = endTime - System.currentTimeMillis();
6721 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006722 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006723 timedout = true;
6724 break;
6725 }
6726 try {
6727 this.wait();
6728 } catch (InterruptedException e) {
6729 }
6730 }
6731 }
6732 }
6733
6734 mUsageStatsService.shutdown();
6735 mBatteryStatsService.shutdown();
6736
6737 return timedout;
6738 }
6739
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006740 public final void activitySlept(IBinder token) {
6741 if (localLOGV) Slog.v(
6742 TAG, "Activity slept: token=" + token);
6743
6744 ActivityRecord r = null;
6745
6746 final long origId = Binder.clearCallingIdentity();
6747
6748 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006749 r = mMainStack.isInStackLocked(token);
6750 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006751 mMainStack.activitySleptLocked(r);
6752 }
6753 }
6754
6755 Binder.restoreCallingIdentity(origId);
6756 }
6757
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006758 private void comeOutOfSleepIfNeededLocked() {
6759 if (!mWentToSleep && !mLockScreenShown) {
6760 if (mSleeping) {
6761 mSleeping = false;
6762 mMainStack.awakeFromSleepingLocked();
6763 mMainStack.resumeTopActivityLocked(null);
6764 }
6765 }
6766 }
6767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006769 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6770 != PackageManager.PERMISSION_GRANTED) {
6771 throw new SecurityException("Requires permission "
6772 + android.Manifest.permission.DEVICE_POWER);
6773 }
6774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006776 mWentToSleep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 mWindowManager.setEventDispatching(true);
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006778 comeOutOfSleepIfNeededLocked();
6779 }
6780 }
6781
6782 public void setLockScreenShown(boolean shown) {
6783 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6784 != PackageManager.PERMISSION_GRANTED) {
6785 throw new SecurityException("Requires permission "
6786 + android.Manifest.permission.DEVICE_POWER);
6787 }
6788
6789 synchronized(this) {
6790 mLockScreenShown = shown;
6791 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 }
6793 }
6794
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006795 public void stopAppSwitches() {
6796 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6797 != PackageManager.PERMISSION_GRANTED) {
6798 throw new SecurityException("Requires permission "
6799 + android.Manifest.permission.STOP_APP_SWITCHES);
6800 }
6801
6802 synchronized(this) {
6803 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6804 + APP_SWITCH_DELAY_TIME;
6805 mDidAppSwitch = false;
6806 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6807 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6808 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6809 }
6810 }
6811
6812 public void resumeAppSwitches() {
6813 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6814 != PackageManager.PERMISSION_GRANTED) {
6815 throw new SecurityException("Requires permission "
6816 + android.Manifest.permission.STOP_APP_SWITCHES);
6817 }
6818
6819 synchronized(this) {
6820 // Note that we don't execute any pending app switches... we will
6821 // let those wait until either the timeout, or the next start
6822 // activity request.
6823 mAppSwitchesAllowedTime = 0;
6824 }
6825 }
6826
6827 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6828 String name) {
6829 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6830 return true;
6831 }
6832
6833 final int perm = checkComponentPermission(
6834 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006835 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006836 if (perm == PackageManager.PERMISSION_GRANTED) {
6837 return true;
6838 }
6839
Joe Onorato8a9b2202010-02-26 18:56:32 -08006840 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006841 return false;
6842 }
6843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 public void setDebugApp(String packageName, boolean waitForDebugger,
6845 boolean persistent) {
6846 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6847 "setDebugApp()");
6848
6849 // Note that this is not really thread safe if there are multiple
6850 // callers into it at the same time, but that's not a situation we
6851 // care about.
6852 if (persistent) {
6853 final ContentResolver resolver = mContext.getContentResolver();
6854 Settings.System.putString(
6855 resolver, Settings.System.DEBUG_APP,
6856 packageName);
6857 Settings.System.putInt(
6858 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6859 waitForDebugger ? 1 : 0);
6860 }
6861
6862 synchronized (this) {
6863 if (!persistent) {
6864 mOrigDebugApp = mDebugApp;
6865 mOrigWaitForDebugger = mWaitForDebugger;
6866 }
6867 mDebugApp = packageName;
6868 mWaitForDebugger = waitForDebugger;
6869 mDebugTransient = !persistent;
6870 if (packageName != null) {
6871 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006872 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 Binder.restoreCallingIdentity(origId);
6874 }
6875 }
6876 }
6877
Siva Velusamy92a8b222012-03-09 16:24:04 -08006878 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6879 synchronized (this) {
6880 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6881 if (!isDebuggable) {
6882 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6883 throw new SecurityException("Process not debuggable: " + app.packageName);
6884 }
6885 }
6886
6887 mOpenGlTraceApp = processName;
6888 }
6889 }
6890
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006891 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6892 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6893 synchronized (this) {
6894 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6895 if (!isDebuggable) {
6896 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6897 throw new SecurityException("Process not debuggable: " + app.packageName);
6898 }
6899 }
6900 mProfileApp = processName;
6901 mProfileFile = profileFile;
6902 if (mProfileFd != null) {
6903 try {
6904 mProfileFd.close();
6905 } catch (IOException e) {
6906 }
6907 mProfileFd = null;
6908 }
6909 mProfileFd = profileFd;
6910 mProfileType = 0;
6911 mAutoStopProfiler = autoStopProfiler;
6912 }
6913 }
6914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 public void setAlwaysFinish(boolean enabled) {
6916 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6917 "setAlwaysFinish()");
6918
6919 Settings.System.putInt(
6920 mContext.getContentResolver(),
6921 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6922
6923 synchronized (this) {
6924 mAlwaysFinishActivities = enabled;
6925 }
6926 }
6927
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006928 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006930 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006932 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 }
6934 }
6935
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006936 public boolean isUserAMonkey() {
6937 // For now the fact that there is a controller implies
6938 // we have a monkey.
6939 synchronized (this) {
6940 return mController != null;
6941 }
6942 }
6943
Jeff Sharkeya4620792011-05-20 15:29:23 -07006944 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006945 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6946 "registerProcessObserver()");
6947 synchronized (this) {
6948 mProcessObservers.register(observer);
6949 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006950 }
6951
6952 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006953 synchronized (this) {
6954 mProcessObservers.unregister(observer);
6955 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006956 }
6957
Daniel Sandler69a48172010-06-23 16:29:36 -04006958 public void setImmersive(IBinder token, boolean immersive) {
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 r.immersive = immersive;
6965 }
6966 }
6967
6968 public boolean isImmersive(IBinder token) {
6969 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006970 ActivityRecord r = mMainStack.isInStackLocked(token);
6971 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006972 throw new IllegalArgumentException();
6973 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006974 return r.immersive;
6975 }
6976 }
6977
6978 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006979 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006980 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006981 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006982 return (r != null) ? r.immersive : false;
6983 }
6984 }
6985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006986 public final void enterSafeMode() {
6987 synchronized(this) {
6988 // It only makes sense to do this before the system is ready
6989 // and started launching other packages.
6990 if (!mSystemReady) {
6991 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006992 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 } catch (RemoteException e) {
6994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006995 }
6996 }
6997 }
6998
Jeff Brownb09abc12011-01-13 21:08:27 -08006999 public final void showSafeModeOverlay() {
7000 View v = LayoutInflater.from(mContext).inflate(
7001 com.android.internal.R.layout.safe_mode, null);
7002 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7003 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7004 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7005 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7006 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7007 lp.format = v.getBackground().getOpacity();
7008 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7009 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7010 ((WindowManager)mContext.getSystemService(
7011 Context.WINDOW_SERVICE)).addView(v, lp);
7012 }
7013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 public void noteWakeupAlarm(IIntentSender sender) {
7015 if (!(sender instanceof PendingIntentRecord)) {
7016 return;
7017 }
7018 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7019 synchronized (stats) {
7020 if (mBatteryStatsService.isOnBattery()) {
7021 mBatteryStatsService.enforceCallingPermission();
7022 PendingIntentRecord rec = (PendingIntentRecord)sender;
7023 int MY_UID = Binder.getCallingUid();
7024 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7025 BatteryStatsImpl.Uid.Pkg pkg =
7026 stats.getPackageStatsLocked(uid, rec.key.packageName);
7027 pkg.incWakeupsLocked();
7028 }
7029 }
7030 }
7031
Dianne Hackborn64825172011-03-02 21:32:58 -08007032 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007034 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007036 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 // XXX Note: don't acquire main activity lock here, because the window
7038 // manager calls in with its locks held.
7039
7040 boolean killed = false;
7041 synchronized (mPidsSelfLocked) {
7042 int[] types = new int[pids.length];
7043 int worstType = 0;
7044 for (int i=0; i<pids.length; i++) {
7045 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7046 if (proc != null) {
7047 int type = proc.setAdj;
7048 types[i] = type;
7049 if (type > worstType) {
7050 worstType = type;
7051 }
7052 }
7053 }
7054
Dianne Hackborn64825172011-03-02 21:32:58 -08007055 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007057 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7058 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007059 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007061
7062 // If this is not a secure call, don't let it kill processes that
7063 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007064 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7065 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007066 }
7067
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007068 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 for (int i=0; i<pids.length; i++) {
7070 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7071 if (proc == null) {
7072 continue;
7073 }
7074 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007075 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007076 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007077 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7078 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007079 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007080 proc.killedBackground = true;
7081 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007082 }
7083 }
7084 }
7085 return killed;
7086 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007087
7088 @Override
7089 public boolean killProcessesBelowForeground(String reason) {
7090 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7091 throw new SecurityException("killProcessesBelowForeground() only available to system");
7092 }
7093
7094 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7095 }
7096
7097 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7098 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7099 throw new SecurityException("killProcessesBelowAdj() only available to system");
7100 }
7101
7102 boolean killed = false;
7103 synchronized (mPidsSelfLocked) {
7104 final int size = mPidsSelfLocked.size();
7105 for (int i = 0; i < size; i++) {
7106 final int pid = mPidsSelfLocked.keyAt(i);
7107 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7108 if (proc == null) continue;
7109
7110 final int adj = proc.setAdj;
7111 if (adj > belowAdj && !proc.killedBackground) {
7112 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7113 EventLog.writeEvent(
7114 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7115 killed = true;
7116 proc.killedBackground = true;
7117 Process.killProcessQuiet(pid);
7118 }
7119 }
7120 }
7121 return killed;
7122 }
7123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 public final void startRunning(String pkg, String cls, String action,
7125 String data) {
7126 synchronized(this) {
7127 if (mStartRunning) {
7128 return;
7129 }
7130 mStartRunning = true;
7131 mTopComponent = pkg != null && cls != null
7132 ? new ComponentName(pkg, cls) : null;
7133 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7134 mTopData = data;
7135 if (!mSystemReady) {
7136 return;
7137 }
7138 }
7139
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007140 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 }
7142
7143 private void retrieveSettings() {
7144 final ContentResolver resolver = mContext.getContentResolver();
7145 String debugApp = Settings.System.getString(
7146 resolver, Settings.System.DEBUG_APP);
7147 boolean waitForDebugger = Settings.System.getInt(
7148 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7149 boolean alwaysFinishActivities = Settings.System.getInt(
7150 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7151
7152 Configuration configuration = new Configuration();
7153 Settings.System.getConfiguration(resolver, configuration);
7154
7155 synchronized (this) {
7156 mDebugApp = mOrigDebugApp = debugApp;
7157 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7158 mAlwaysFinishActivities = alwaysFinishActivities;
7159 // This happens before any activities are started, so we can
7160 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007161 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007162 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 }
7164 }
7165
7166 public boolean testIsSystemReady() {
7167 // no need to synchronize(this) just to read & return the value
7168 return mSystemReady;
7169 }
7170
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007171 private static File getCalledPreBootReceiversFile() {
7172 File dataDir = Environment.getDataDirectory();
7173 File systemDir = new File(dataDir, "system");
7174 File fname = new File(systemDir, "called_pre_boots.dat");
7175 return fname;
7176 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007177
7178 static final int LAST_DONE_VERSION = 10000;
7179
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007180 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7181 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7182 File file = getCalledPreBootReceiversFile();
7183 FileInputStream fis = null;
7184 try {
7185 fis = new FileInputStream(file);
7186 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007187 int fvers = dis.readInt();
7188 if (fvers == LAST_DONE_VERSION) {
7189 String vers = dis.readUTF();
7190 String codename = dis.readUTF();
7191 String build = dis.readUTF();
7192 if (android.os.Build.VERSION.RELEASE.equals(vers)
7193 && android.os.Build.VERSION.CODENAME.equals(codename)
7194 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7195 int num = dis.readInt();
7196 while (num > 0) {
7197 num--;
7198 String pkg = dis.readUTF();
7199 String cls = dis.readUTF();
7200 lastDoneReceivers.add(new ComponentName(pkg, cls));
7201 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007202 }
7203 }
7204 } catch (FileNotFoundException e) {
7205 } catch (IOException e) {
7206 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7207 } finally {
7208 if (fis != null) {
7209 try {
7210 fis.close();
7211 } catch (IOException e) {
7212 }
7213 }
7214 }
7215 return lastDoneReceivers;
7216 }
7217
7218 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7219 File file = getCalledPreBootReceiversFile();
7220 FileOutputStream fos = null;
7221 DataOutputStream dos = null;
7222 try {
7223 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7224 fos = new FileOutputStream(file);
7225 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007226 dos.writeInt(LAST_DONE_VERSION);
7227 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007228 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007229 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007230 dos.writeInt(list.size());
7231 for (int i=0; i<list.size(); i++) {
7232 dos.writeUTF(list.get(i).getPackageName());
7233 dos.writeUTF(list.get(i).getClassName());
7234 }
7235 } catch (IOException e) {
7236 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7237 file.delete();
7238 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007239 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007240 if (dos != null) {
7241 try {
7242 dos.close();
7243 } catch (IOException e) {
7244 // TODO Auto-generated catch block
7245 e.printStackTrace();
7246 }
7247 }
7248 }
7249 }
7250
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007251 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 synchronized(this) {
7253 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007254 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 return;
7256 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007257
7258 // Check to see if there are any update receivers to run.
7259 if (!mDidUpdate) {
7260 if (mWaitingUpdate) {
7261 return;
7262 }
7263 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7264 List<ResolveInfo> ris = null;
7265 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007266 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007267 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007268 } catch (RemoteException e) {
7269 }
7270 if (ris != null) {
7271 for (int i=ris.size()-1; i>=0; i--) {
7272 if ((ris.get(i).activityInfo.applicationInfo.flags
7273 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7274 ris.remove(i);
7275 }
7276 }
7277 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007278
7279 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7280
7281 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007282 for (int i=0; i<ris.size(); i++) {
7283 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007284 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7285 if (lastDoneReceivers.contains(comp)) {
7286 ris.remove(i);
7287 i--;
7288 }
7289 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007290
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007291 for (int i=0; i<ris.size(); i++) {
7292 ActivityInfo ai = ris.get(i).activityInfo;
7293 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7294 doneReceivers.add(comp);
7295 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007296 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007297 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007298 finisher = new IIntentReceiver.Stub() {
7299 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007300 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007301 boolean sticky) {
7302 // The raw IIntentReceiver interface is called
7303 // with the AM lock held, so redispatch to
7304 // execute our code without the lock.
7305 mHandler.post(new Runnable() {
7306 public void run() {
7307 synchronized (ActivityManagerService.this) {
7308 mDidUpdate = true;
7309 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007310 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007311 showBootMessage(mContext.getText(
7312 R.string.android_upgrading_complete),
7313 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007314 systemReady(goingCallback);
7315 }
7316 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007317 }
7318 };
7319 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007320 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007321 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007322 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007323 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007324 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007325 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007326 mWaitingUpdate = true;
7327 }
7328 }
7329 }
7330 if (mWaitingUpdate) {
7331 return;
7332 }
7333 mDidUpdate = true;
7334 }
7335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 mSystemReady = true;
7337 if (!mStartRunning) {
7338 return;
7339 }
7340 }
7341
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007342 ArrayList<ProcessRecord> procsToKill = null;
7343 synchronized(mPidsSelfLocked) {
7344 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7345 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7346 if (!isAllowedWhileBooting(proc.info)){
7347 if (procsToKill == null) {
7348 procsToKill = new ArrayList<ProcessRecord>();
7349 }
7350 procsToKill.add(proc);
7351 }
7352 }
7353 }
7354
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007355 synchronized(this) {
7356 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007357 for (int i=procsToKill.size()-1; i>=0; i--) {
7358 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007359 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007360 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007361 }
7362 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007363
7364 // Now that we have cleaned up any update processes, we
7365 // are ready to start launching real processes and know that
7366 // we won't trample on them any more.
7367 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007368 }
7369
Joe Onorato8a9b2202010-02-26 18:56:32 -08007370 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007371 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007372 SystemClock.uptimeMillis());
7373
7374 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007375 // Make sure we have no pre-ready processes sitting around.
7376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7378 ResolveInfo ri = mContext.getPackageManager()
7379 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007380 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 CharSequence errorMsg = null;
7382 if (ri != null) {
7383 ActivityInfo ai = ri.activityInfo;
7384 ApplicationInfo app = ai.applicationInfo;
7385 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7386 mTopAction = Intent.ACTION_FACTORY_TEST;
7387 mTopData = null;
7388 mTopComponent = new ComponentName(app.packageName,
7389 ai.name);
7390 } else {
7391 errorMsg = mContext.getResources().getText(
7392 com.android.internal.R.string.factorytest_not_system);
7393 }
7394 } else {
7395 errorMsg = mContext.getResources().getText(
7396 com.android.internal.R.string.factorytest_no_action);
7397 }
7398 if (errorMsg != null) {
7399 mTopAction = null;
7400 mTopData = null;
7401 mTopComponent = null;
7402 Message msg = Message.obtain();
7403 msg.what = SHOW_FACTORY_ERROR_MSG;
7404 msg.getData().putCharSequence("msg", errorMsg);
7405 mHandler.sendMessage(msg);
7406 }
7407 }
7408 }
7409
7410 retrieveSettings();
7411
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007412 if (goingCallback != null) goingCallback.run();
7413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 synchronized (this) {
7415 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7416 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007417 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007418 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 if (apps != null) {
7420 int N = apps.size();
7421 int i;
7422 for (i=0; i<N; i++) {
7423 ApplicationInfo info
7424 = (ApplicationInfo)apps.get(i);
7425 if (info != null &&
7426 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007427 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 }
7429 }
7430 }
7431 } catch (RemoteException ex) {
7432 // pm is in same process, this will never happen.
7433 }
7434 }
7435
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007436 // Start up initial activity.
7437 mBooting = true;
7438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007440 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 Message msg = Message.obtain();
7442 msg.what = SHOW_UID_ERROR_MSG;
7443 mHandler.sendMessage(msg);
7444 }
7445 } catch (RemoteException e) {
7446 }
7447
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007448 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 }
7450 }
7451
Dan Egnorb7f03672009-12-09 16:22:32 -08007452 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007453 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007455 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007456 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 startAppProblemLocked(app);
7458 app.stopFreezingAllLocked();
7459 return handleAppCrashLocked(app);
7460 }
7461
Dan Egnorb7f03672009-12-09 16:22:32 -08007462 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007463 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007465 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007466 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7467 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 startAppProblemLocked(app);
7469 app.stopFreezingAllLocked();
7470 }
7471
7472 /**
7473 * Generate a process error record, suitable for attachment to a ProcessRecord.
7474 *
7475 * @param app The ProcessRecord in which the error occurred.
7476 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7477 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007478 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007479 * @param shortMsg Short message describing the crash.
7480 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007481 * @param stackTrace Full crash stack trace, may be null.
7482 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 * @return Returns a fully-formed AppErrorStateInfo record.
7484 */
7485 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007486 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 report.condition = condition;
7490 report.processName = app.processName;
7491 report.pid = app.pid;
7492 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007493 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 report.shortMsg = shortMsg;
7495 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007496 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497
7498 return report;
7499 }
7500
Dan Egnor42471dd2010-01-07 17:25:22 -08007501 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 synchronized (this) {
7503 app.crashing = false;
7504 app.crashingReport = null;
7505 app.notResponding = false;
7506 app.notRespondingReport = null;
7507 if (app.anrDialog == fromDialog) {
7508 app.anrDialog = null;
7509 }
7510 if (app.waitDialog == fromDialog) {
7511 app.waitDialog = null;
7512 }
7513 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007514 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007515 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007516 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7517 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007518 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 }
7521 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007522
Dan Egnorb7f03672009-12-09 16:22:32 -08007523 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007524 if (mHeadless) {
7525 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7526 return false;
7527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007528 long now = SystemClock.uptimeMillis();
7529
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007530 Long crashTime;
7531 if (!app.isolated) {
7532 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7533 } else {
7534 crashTime = null;
7535 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007536 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007538 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007540 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007541 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007542 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7543 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007545 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007547 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 }
7549 }
7550 if (!app.persistent) {
7551 // We don't want to start this process again until the user
7552 // explicitly does so... but for persistent process, we really
7553 // need to keep it running. If a persistent process is actually
7554 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007555 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007557 if (!app.isolated) {
7558 // XXX We don't have a way to mark isolated processes
7559 // as bad, since they don't have a peristent identity.
7560 mBadProcesses.put(app.info.processName, app.uid, now);
7561 mProcessCrashTimes.remove(app.info.processName, app.uid);
7562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007565 // Don't let services in this process be restarted and potentially
7566 // annoy the user repeatedly. Unless it is persistent, since those
7567 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007568 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007569 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 return false;
7571 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007572 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007573 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007574 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007575 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007576 // If the top running activity is from this crashing
7577 // process, then terminate it to avoid getting in a loop.
7578 Slog.w(TAG, " Force finishing activity "
7579 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007580 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007581 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007582 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007583 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007584 // stopped, to avoid a situation where one will get
7585 // re-start our crashing activity once it gets resumed again.
7586 index--;
7587 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007588 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007589 if (r.state == ActivityState.RESUMED
7590 || r.state == ActivityState.PAUSING
7591 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007592 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007593 Slog.w(TAG, " Force finishing activity "
7594 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007595 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007596 Activity.RESULT_CANCELED, null, "crashed");
7597 }
7598 }
7599 }
7600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 }
7602
7603 // Bump up the crash count of any services currently running in the proc.
7604 if (app.services.size() != 0) {
7605 // Any services running in the application need to be placed
7606 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007607 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007609 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 sr.crashCount++;
7611 }
7612 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007613
7614 // If the crashing process is what we consider to be the "home process" and it has been
7615 // replaced by a third-party app, clear the package preferred activities from packages
7616 // with a home activity running in the process to prevent a repeatedly crashing app
7617 // from blocking the user to manually clear the list.
7618 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7619 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7620 Iterator it = mHomeProcess.activities.iterator();
7621 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007622 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007623 if (r.isHomeActivity) {
7624 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7625 try {
7626 ActivityThread.getPackageManager()
7627 .clearPackagePreferredActivities(r.packageName);
7628 } catch (RemoteException c) {
7629 // pm is in same process, this will never happen.
7630 }
7631 }
7632 }
7633 }
7634
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007635 if (!app.isolated) {
7636 // XXX Can't keep track of crash times for isolated processes,
7637 // because they don't have a perisistent identity.
7638 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7639 }
7640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 return true;
7642 }
7643
7644 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007645 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7646 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007647 skipCurrentReceiverLocked(app);
7648 }
7649
7650 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007651 for (BroadcastQueue queue : mBroadcastQueues) {
7652 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 }
7654 }
7655
Dan Egnor60d87622009-12-16 16:32:58 -08007656 /**
7657 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7658 * The application process will exit immediately after this call returns.
7659 * @param app object of the crashing app, null for the system server
7660 * @param crashInfo describing the exception
7661 */
7662 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007663 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007664 final String processName = app == null ? "system_server"
7665 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007666
7667 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007668 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007669 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007670 crashInfo.exceptionClassName,
7671 crashInfo.exceptionMessage,
7672 crashInfo.throwFileName,
7673 crashInfo.throwLineNumber);
7674
Jeff Sharkeya353d262011-10-28 11:12:06 -07007675 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007676
7677 crashApplication(r, crashInfo);
7678 }
7679
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007680 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007681 IBinder app,
7682 int violationMask,
7683 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007684 ProcessRecord r = findAppProcess(app, "StrictMode");
7685 if (r == null) {
7686 return;
7687 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007688
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007689 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007690 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007691 boolean logIt = true;
7692 synchronized (mAlreadyLoggedViolatedStacks) {
7693 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7694 logIt = false;
7695 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007696 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007697 // the relative pain numbers, without logging all
7698 // the stack traces repeatedly. We'd want to do
7699 // likewise in the client code, which also does
7700 // dup suppression, before the Binder call.
7701 } else {
7702 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7703 mAlreadyLoggedViolatedStacks.clear();
7704 }
7705 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7706 }
7707 }
7708 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007709 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007710 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007711 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007712
7713 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7714 AppErrorResult result = new AppErrorResult();
7715 synchronized (this) {
7716 final long origId = Binder.clearCallingIdentity();
7717
7718 Message msg = Message.obtain();
7719 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7720 HashMap<String, Object> data = new HashMap<String, Object>();
7721 data.put("result", result);
7722 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007723 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007724 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007725 msg.obj = data;
7726 mHandler.sendMessage(msg);
7727
7728 Binder.restoreCallingIdentity(origId);
7729 }
7730 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007731 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007732 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007733 }
7734
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007735 // Depending on the policy in effect, there could be a bunch of
7736 // these in quick succession so we try to batch these together to
7737 // minimize disk writes, number of dropbox entries, and maximize
7738 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007739 private void logStrictModeViolationToDropBox(
7740 ProcessRecord process,
7741 StrictMode.ViolationInfo info) {
7742 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007743 return;
7744 }
7745 final boolean isSystemApp = process == null ||
7746 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7747 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007748 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007749 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7750 final DropBoxManager dbox = (DropBoxManager)
7751 mContext.getSystemService(Context.DROPBOX_SERVICE);
7752
7753 // Exit early if the dropbox isn't configured to accept this report type.
7754 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7755
7756 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007757 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007758 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7759 synchronized (sb) {
7760 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007761 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007762 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7763 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007764 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7765 if (info.violationNumThisLoop != 0) {
7766 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7767 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007768 if (info.numAnimationsRunning != 0) {
7769 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7770 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007771 if (info.broadcastIntentAction != null) {
7772 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7773 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007774 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007775 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007776 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007777 if (info.numInstances != -1) {
7778 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7779 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007780 if (info.tags != null) {
7781 for (String tag : info.tags) {
7782 sb.append("Span-Tag: ").append(tag).append("\n");
7783 }
7784 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007785 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007786 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7787 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007788 }
7789 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007790
7791 // Only buffer up to ~64k. Various logging bits truncate
7792 // things at 128k.
7793 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007794 }
7795
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007796 // Flush immediately if the buffer's grown too large, or this
7797 // is a non-system app. Non-system apps are isolated with a
7798 // different tag & policy and not batched.
7799 //
7800 // Batching is useful during internal testing with
7801 // StrictMode settings turned up high. Without batching,
7802 // thousands of separate files could be created on boot.
7803 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007804 new Thread("Error dump: " + dropboxTag) {
7805 @Override
7806 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007807 String report;
7808 synchronized (sb) {
7809 report = sb.toString();
7810 sb.delete(0, sb.length());
7811 sb.trimToSize();
7812 }
7813 if (report.length() != 0) {
7814 dbox.addText(dropboxTag, report);
7815 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007816 }
7817 }.start();
7818 return;
7819 }
7820
7821 // System app batching:
7822 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007823 // An existing dropbox-writing thread is outstanding, so
7824 // we don't need to start it up. The existing thread will
7825 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007826 return;
7827 }
7828
7829 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7830 // (After this point, we shouldn't access AMS internal data structures.)
7831 new Thread("Error dump: " + dropboxTag) {
7832 @Override
7833 public void run() {
7834 // 5 second sleep to let stacks arrive and be batched together
7835 try {
7836 Thread.sleep(5000); // 5 seconds
7837 } catch (InterruptedException e) {}
7838
7839 String errorReport;
7840 synchronized (mStrictModeBuffer) {
7841 errorReport = mStrictModeBuffer.toString();
7842 if (errorReport.length() == 0) {
7843 return;
7844 }
7845 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7846 mStrictModeBuffer.trimToSize();
7847 }
7848 dbox.addText(dropboxTag, errorReport);
7849 }
7850 }.start();
7851 }
7852
Dan Egnor60d87622009-12-16 16:32:58 -08007853 /**
7854 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7855 * @param app object of the crashing app, null for the system server
7856 * @param tag reported by the caller
7857 * @param crashInfo describing the context of the error
7858 * @return true if the process should exit immediately (WTF is fatal)
7859 */
7860 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007861 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007862 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007863 final String processName = app == null ? "system_server"
7864 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007865
7866 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007867 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007868 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007869 tag, crashInfo.exceptionMessage);
7870
Jeff Sharkeya353d262011-10-28 11:12:06 -07007871 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007872
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007873 if (r != null && r.pid != Process.myPid() &&
7874 Settings.Secure.getInt(mContext.getContentResolver(),
7875 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007876 crashApplication(r, crashInfo);
7877 return true;
7878 } else {
7879 return false;
7880 }
7881 }
7882
7883 /**
7884 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7885 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7886 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007887 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007888 if (app == null) {
7889 return null;
7890 }
7891
7892 synchronized (this) {
7893 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7894 final int NA = apps.size();
7895 for (int ia=0; ia<NA; ia++) {
7896 ProcessRecord p = apps.valueAt(ia);
7897 if (p.thread != null && p.thread.asBinder() == app) {
7898 return p;
7899 }
7900 }
7901 }
7902
Dianne Hackborncb44d962011-03-10 17:02:27 -08007903 Slog.w(TAG, "Can't find mystery application for " + reason
7904 + " from pid=" + Binder.getCallingPid()
7905 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007906 return null;
7907 }
7908 }
7909
7910 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007911 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7912 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007913 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007914 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7915 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007916 // Watchdog thread ends up invoking this function (with
7917 // a null ProcessRecord) to add the stack file to dropbox.
7918 // Do not acquire a lock on this (am) in such cases, as it
7919 // could cause a potential deadlock, if and when watchdog
7920 // is invoked due to unavailability of lock on am and it
7921 // would prevent watchdog from killing system_server.
7922 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007923 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007924 return;
7925 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007926 // Note: ProcessRecord 'process' is guarded by the service
7927 // instance. (notably process.pkgList, which could otherwise change
7928 // concurrently during execution of this method)
7929 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007930 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007931 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007932 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007933 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7934 for (String pkg : process.pkgList) {
7935 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007936 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007937 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007938 if (pi != null) {
7939 sb.append(" v").append(pi.versionCode);
7940 if (pi.versionName != null) {
7941 sb.append(" (").append(pi.versionName).append(")");
7942 }
7943 }
7944 } catch (RemoteException e) {
7945 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007946 }
Dan Egnora455d192010-03-12 08:52:28 -08007947 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007948 }
Dan Egnora455d192010-03-12 08:52:28 -08007949 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007950 }
7951
7952 private static String processClass(ProcessRecord process) {
7953 if (process == null || process.pid == MY_PID) {
7954 return "system_server";
7955 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7956 return "system_app";
7957 } else {
7958 return "data_app";
7959 }
7960 }
7961
7962 /**
7963 * Write a description of an error (crash, WTF, ANR) to the drop box.
7964 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7965 * @param process which caused the error, null means the system server
7966 * @param activity which triggered the error, null if unknown
7967 * @param parent activity related to the error, null if unknown
7968 * @param subject line related to the error, null if absent
7969 * @param report in long form describing the error, null if absent
7970 * @param logFile to include in the report, null if none
7971 * @param crashInfo giving an application stack trace, null if absent
7972 */
7973 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007974 ProcessRecord process, String processName, ActivityRecord activity,
7975 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007976 final String report, final File logFile,
7977 final ApplicationErrorReport.CrashInfo crashInfo) {
7978 // NOTE -- this must never acquire the ActivityManagerService lock,
7979 // otherwise the watchdog may be prevented from resetting the system.
7980
7981 final String dropboxTag = processClass(process) + "_" + eventType;
7982 final DropBoxManager dbox = (DropBoxManager)
7983 mContext.getSystemService(Context.DROPBOX_SERVICE);
7984
7985 // Exit early if the dropbox isn't configured to accept this report type.
7986 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7987
7988 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007989 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007990 if (activity != null) {
7991 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7992 }
7993 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7994 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7995 }
7996 if (parent != null && parent != activity) {
7997 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7998 }
7999 if (subject != null) {
8000 sb.append("Subject: ").append(subject).append("\n");
8001 }
8002 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008003 if (Debug.isDebuggerConnected()) {
8004 sb.append("Debugger: Connected\n");
8005 }
Dan Egnora455d192010-03-12 08:52:28 -08008006 sb.append("\n");
8007
8008 // Do the rest in a worker thread to avoid blocking the caller on I/O
8009 // (After this point, we shouldn't access AMS internal data structures.)
8010 Thread worker = new Thread("Error dump: " + dropboxTag) {
8011 @Override
8012 public void run() {
8013 if (report != null) {
8014 sb.append(report);
8015 }
8016 if (logFile != null) {
8017 try {
8018 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8019 } catch (IOException e) {
8020 Slog.e(TAG, "Error reading " + logFile, e);
8021 }
8022 }
8023 if (crashInfo != null && crashInfo.stackTrace != null) {
8024 sb.append(crashInfo.stackTrace);
8025 }
8026
8027 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8028 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8029 if (lines > 0) {
8030 sb.append("\n");
8031
8032 // Merge several logcat streams, and take the last N lines
8033 InputStreamReader input = null;
8034 try {
8035 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8036 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8037 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8038
8039 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8040 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8041 input = new InputStreamReader(logcat.getInputStream());
8042
8043 int num;
8044 char[] buf = new char[8192];
8045 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8046 } catch (IOException e) {
8047 Slog.e(TAG, "Error running logcat", e);
8048 } finally {
8049 if (input != null) try { input.close(); } catch (IOException e) {}
8050 }
8051 }
8052
8053 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008054 }
Dan Egnora455d192010-03-12 08:52:28 -08008055 };
8056
8057 if (process == null || process.pid == MY_PID) {
8058 worker.run(); // We may be about to die -- need to run this synchronously
8059 } else {
8060 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008061 }
8062 }
8063
8064 /**
8065 * Bring up the "unexpected error" dialog box for a crashing app.
8066 * Deal with edge cases (intercepts from instrumented applications,
8067 * ActivityController, error intent receivers, that sort of thing).
8068 * @param r the application crashing
8069 * @param crashInfo describing the failure
8070 */
8071 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008072 long timeMillis = System.currentTimeMillis();
8073 String shortMsg = crashInfo.exceptionClassName;
8074 String longMsg = crashInfo.exceptionMessage;
8075 String stackTrace = crashInfo.stackTrace;
8076 if (shortMsg != null && longMsg != null) {
8077 longMsg = shortMsg + ": " + longMsg;
8078 } else if (shortMsg != null) {
8079 longMsg = shortMsg;
8080 }
8081
Dan Egnor60d87622009-12-16 16:32:58 -08008082 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008084 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 try {
8086 String name = r != null ? r.processName : null;
8087 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008088 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008089 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008090 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 + " at watcher's request");
8092 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008093 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 }
8095 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008096 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 }
8098 }
8099
8100 final long origId = Binder.clearCallingIdentity();
8101
8102 // If this process is running instrumentation, finish it.
8103 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008104 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008106 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8107 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 Bundle info = new Bundle();
8109 info.putString("shortMsg", shortMsg);
8110 info.putString("longMsg", longMsg);
8111 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8112 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008113 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 }
8115
Dan Egnor60d87622009-12-16 16:32:58 -08008116 // If we can't identify the process or it's already exceeded its crash quota,
8117 // quit right away without showing a crash dialog.
8118 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008119 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008120 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008121 }
8122
8123 Message msg = Message.obtain();
8124 msg.what = SHOW_ERROR_MSG;
8125 HashMap data = new HashMap();
8126 data.put("result", result);
8127 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 msg.obj = data;
8129 mHandler.sendMessage(msg);
8130
8131 Binder.restoreCallingIdentity(origId);
8132 }
8133
8134 int res = result.get();
8135
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008136 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008138 if (r != null && !r.isolated) {
8139 // XXX Can't keep track of crash time for isolated processes,
8140 // since they don't have a persistent identity.
8141 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008142 SystemClock.uptimeMillis());
8143 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008144 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008145 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008146 }
8147 }
8148
8149 if (appErrorIntent != null) {
8150 try {
8151 mContext.startActivity(appErrorIntent);
8152 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008153 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008157
8158 Intent createAppErrorIntentLocked(ProcessRecord r,
8159 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8160 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008161 if (report == null) {
8162 return null;
8163 }
8164 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8165 result.setComponent(r.errorReportReceiver);
8166 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8167 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8168 return result;
8169 }
8170
Dan Egnorb7f03672009-12-09 16:22:32 -08008171 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8172 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008173 if (r.errorReportReceiver == null) {
8174 return null;
8175 }
8176
8177 if (!r.crashing && !r.notResponding) {
8178 return null;
8179 }
8180
Dan Egnorb7f03672009-12-09 16:22:32 -08008181 ApplicationErrorReport report = new ApplicationErrorReport();
8182 report.packageName = r.info.packageName;
8183 report.installerPackageName = r.errorReportReceiver.getPackageName();
8184 report.processName = r.processName;
8185 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008186 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008187
Dan Egnorb7f03672009-12-09 16:22:32 -08008188 if (r.crashing) {
8189 report.type = ApplicationErrorReport.TYPE_CRASH;
8190 report.crashInfo = crashInfo;
8191 } else if (r.notResponding) {
8192 report.type = ApplicationErrorReport.TYPE_ANR;
8193 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008194
Dan Egnorb7f03672009-12-09 16:22:32 -08008195 report.anrInfo.activity = r.notRespondingReport.tag;
8196 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8197 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008198 }
8199
Dan Egnorb7f03672009-12-09 16:22:32 -08008200 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008201 }
8202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008204 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008205 // assume our apps are happy - lazy create the list
8206 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8207
8208 synchronized (this) {
8209
8210 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008211 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8212 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8214 // This one's in trouble, so we'll generate a report for it
8215 // crashes are higher priority (in case there's a crash *and* an anr)
8216 ActivityManager.ProcessErrorStateInfo report = null;
8217 if (app.crashing) {
8218 report = app.crashingReport;
8219 } else if (app.notResponding) {
8220 report = app.notRespondingReport;
8221 }
8222
8223 if (report != null) {
8224 if (errList == null) {
8225 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8226 }
8227 errList.add(report);
8228 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008229 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008230 " crashing = " + app.crashing +
8231 " notResponding = " + app.notResponding);
8232 }
8233 }
8234 }
8235 }
8236
8237 return errList;
8238 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008239
8240 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008241 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008242 if (currApp != null) {
8243 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8244 }
8245 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008246 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8247 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008248 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8249 if (currApp != null) {
8250 currApp.lru = 0;
8251 }
8252 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008253 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008254 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8255 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8256 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8257 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8258 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8259 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8260 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8261 } else {
8262 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8263 }
8264 }
8265
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008266 private void fillInProcMemInfo(ProcessRecord app,
8267 ActivityManager.RunningAppProcessInfo outInfo) {
8268 outInfo.pid = app.pid;
8269 outInfo.uid = app.info.uid;
8270 if (mHeavyWeightProcess == app) {
8271 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8272 }
8273 if (app.persistent) {
8274 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8275 }
8276 outInfo.lastTrimLevel = app.trimMemoryLevel;
8277 int adj = app.curAdj;
8278 outInfo.importance = oomAdjToImportance(adj, outInfo);
8279 outInfo.importanceReasonCode = app.adjTypeCode;
8280 }
8281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008283 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 // Lazy instantiation of list
8285 List<ActivityManager.RunningAppProcessInfo> runList = null;
8286 synchronized (this) {
8287 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008288 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8289 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8291 // Generate process state info for running application
8292 ActivityManager.RunningAppProcessInfo currApp =
8293 new ActivityManager.RunningAppProcessInfo(app.processName,
8294 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008295 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008296 if (app.adjSource instanceof ProcessRecord) {
8297 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008298 currApp.importanceReasonImportance = oomAdjToImportance(
8299 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008300 } else if (app.adjSource instanceof ActivityRecord) {
8301 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008302 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8303 }
8304 if (app.adjTarget instanceof ComponentName) {
8305 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8306 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008307 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008308 // + " lru=" + currApp.lru);
8309 if (runList == null) {
8310 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8311 }
8312 runList.add(currApp);
8313 }
8314 }
8315 }
8316 return runList;
8317 }
8318
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008319 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008320 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008321 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8322 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8323 if (runningApps != null && runningApps.size() > 0) {
8324 Set<String> extList = new HashSet<String>();
8325 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8326 if (app.pkgList != null) {
8327 for (String pkg : app.pkgList) {
8328 extList.add(pkg);
8329 }
8330 }
8331 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008332 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008333 for (String pkg : extList) {
8334 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008335 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008336 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8337 retList.add(info);
8338 }
8339 } catch (RemoteException e) {
8340 }
8341 }
8342 }
8343 return retList;
8344 }
8345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008347 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8348 enforceNotIsolatedCaller("getMyMemoryState");
8349 synchronized (this) {
8350 ProcessRecord proc;
8351 synchronized (mPidsSelfLocked) {
8352 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8353 }
8354 fillInProcMemInfo(proc, outInfo);
8355 }
8356 }
8357
8358 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008360 if (checkCallingPermission(android.Manifest.permission.DUMP)
8361 != PackageManager.PERMISSION_GRANTED) {
8362 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8363 + Binder.getCallingPid()
8364 + ", uid=" + Binder.getCallingUid()
8365 + " without permission "
8366 + android.Manifest.permission.DUMP);
8367 return;
8368 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008369
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008370 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008371 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008372 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008373
8374 int opti = 0;
8375 while (opti < args.length) {
8376 String opt = args[opti];
8377 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8378 break;
8379 }
8380 opti++;
8381 if ("-a".equals(opt)) {
8382 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008383 } else if ("-c".equals(opt)) {
8384 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008385 } else if ("-h".equals(opt)) {
8386 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008387 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008388 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008389 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008390 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8391 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8392 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008393 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008394 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008395 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008396 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008397 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008398 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008399 pw.println(" all: dump all activities");
8400 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008401 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008402 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8403 pw.println(" a partial substring in a component name, a");
8404 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008405 pw.println(" -a: include all available server state.");
8406 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008408 } else {
8409 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008411 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008412
8413 long origId = Binder.clearCallingIdentity();
8414 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008415 // Is the caller requesting to dump a particular piece of data?
8416 if (opti < args.length) {
8417 String cmd = args[opti];
8418 opti++;
8419 if ("activities".equals(cmd) || "a".equals(cmd)) {
8420 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008421 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008422 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008423 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008424 String[] newArgs;
8425 String name;
8426 if (opti >= args.length) {
8427 name = null;
8428 newArgs = EMPTY_STRING_ARRAY;
8429 } else {
8430 name = args[opti];
8431 opti++;
8432 newArgs = new String[args.length - opti];
8433 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8434 args.length - opti);
8435 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008436 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008437 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008438 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008439 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008440 String[] newArgs;
8441 String name;
8442 if (opti >= args.length) {
8443 name = null;
8444 newArgs = EMPTY_STRING_ARRAY;
8445 } else {
8446 name = args[opti];
8447 opti++;
8448 newArgs = new String[args.length - opti];
8449 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8450 args.length - opti);
8451 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008452 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008453 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008454 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008455 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008456 String[] newArgs;
8457 String name;
8458 if (opti >= args.length) {
8459 name = null;
8460 newArgs = EMPTY_STRING_ARRAY;
8461 } else {
8462 name = args[opti];
8463 opti++;
8464 newArgs = new String[args.length - opti];
8465 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8466 args.length - opti);
8467 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008468 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008469 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008470 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008471 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8472 synchronized (this) {
8473 dumpOomLocked(fd, pw, args, opti, true);
8474 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008475 } else if ("provider".equals(cmd)) {
8476 String[] newArgs;
8477 String name;
8478 if (opti >= args.length) {
8479 name = null;
8480 newArgs = EMPTY_STRING_ARRAY;
8481 } else {
8482 name = args[opti];
8483 opti++;
8484 newArgs = new String[args.length - opti];
8485 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8486 }
8487 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8488 pw.println("No providers match: " + name);
8489 pw.println("Use -h for help.");
8490 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008491 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8492 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008493 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008494 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008496 String[] newArgs;
8497 String name;
8498 if (opti >= args.length) {
8499 name = null;
8500 newArgs = EMPTY_STRING_ARRAY;
8501 } else {
8502 name = args[opti];
8503 opti++;
8504 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008505 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8506 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008507 }
8508 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8509 pw.println("No services match: " + name);
8510 pw.println("Use -h for help.");
8511 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008512 } else if ("package".equals(cmd)) {
8513 String[] newArgs;
8514 if (opti >= args.length) {
8515 pw.println("package: no package name specified");
8516 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008517 } else {
8518 dumpPackage = args[opti];
8519 opti++;
8520 newArgs = new String[args.length - opti];
8521 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8522 args.length - opti);
8523 args = newArgs;
8524 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008525 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008526 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008527 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8528 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008529 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008530 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008531 } else {
8532 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008533 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8534 pw.println("Bad activity command, or no activities match: " + cmd);
8535 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008536 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008537 }
8538 if (!more) {
8539 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008540 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008542 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008543
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008544 // No piece of data specified, dump everything.
8545 synchronized (this) {
8546 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008547 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548 if (needSep) {
8549 pw.println(" ");
8550 }
8551 if (dumpAll) {
8552 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008553 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008554 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008555 if (needSep) {
8556 pw.println(" ");
8557 }
8558 if (dumpAll) {
8559 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008560 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008561 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008562 if (needSep) {
8563 pw.println(" ");
8564 }
8565 if (dumpAll) {
8566 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008567 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008568 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008569 if (needSep) {
8570 pw.println(" ");
8571 }
8572 if (dumpAll) {
8573 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008574 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008575 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008576 if (needSep) {
8577 pw.println(" ");
8578 }
8579 if (dumpAll) {
8580 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008582 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008583 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008584 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008586
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008587 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008588 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008589 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8590 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008591 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8592 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593 pw.println(" ");
8594 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008595 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8596 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008597 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008600 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008601 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008602 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008603 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008606 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008607 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008608 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008609 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8610 pw.println(" ");
8611 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008612 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008613 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008614 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008615 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008616 pw.println(" ");
8617 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008618 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008619 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008622 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008623 if (mMainStack.mPausingActivity != null) {
8624 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008625 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008626 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008627 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008628 if (dumpAll) {
8629 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8630 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008631 pw.println(" mDismissKeyguardOnNextActivity: "
8632 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008635 if (mRecentTasks.size() > 0) {
8636 pw.println();
8637 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008638
8639 final int N = mRecentTasks.size();
8640 for (int i=0; i<N; i++) {
8641 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008642 if (dumpPackage != null) {
8643 if (tr.realActivity == null ||
8644 !dumpPackage.equals(tr.realActivity)) {
8645 continue;
8646 }
8647 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008648 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8649 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008650 if (dumpAll) {
8651 mRecentTasks.get(i).dump(pw, " ");
8652 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008653 }
8654 }
8655
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008656 if (dumpAll) {
8657 pw.println(" ");
8658 pw.println(" mCurTask: " + mCurTask);
8659 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008660
8661 return true;
8662 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008663
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008664 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008665 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008666 boolean needSep = false;
8667 int numPers = 0;
8668
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008669 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8670
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008671 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8673 final int NA = procs.size();
8674 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008675 ProcessRecord r = procs.valueAt(ia);
8676 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8677 continue;
8678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679 if (!needSep) {
8680 pw.println(" All known processes:");
8681 needSep = true;
8682 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008683 pw.print(r.persistent ? " *PERS*" : " *APP*");
8684 pw.print(" UID "); pw.print(procs.keyAt(ia));
8685 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 r.dump(pw, " ");
8687 if (r.persistent) {
8688 numPers++;
8689 }
8690 }
8691 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008692 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008693
8694 if (mIsolatedProcesses.size() > 0) {
8695 if (needSep) pw.println(" ");
8696 needSep = true;
8697 pw.println(" Isolated process list (sorted by uid):");
8698 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8699 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8700 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8701 continue;
8702 }
8703 pw.println(String.format("%sIsolated #%2d: %s",
8704 " ", i, r.toString()));
8705 }
8706 }
8707
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 if (mLruProcesses.size() > 0) {
8709 if (needSep) pw.println(" ");
8710 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008711 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008712 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008713 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008714 needSep = true;
8715 }
8716
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008717 if (dumpAll) {
8718 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008719 boolean printed = false;
8720 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8721 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8722 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8723 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008724 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008725 if (!printed) {
8726 if (needSep) pw.println(" ");
8727 needSep = true;
8728 pw.println(" PID mappings:");
8729 printed = true;
8730 }
8731 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8732 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 }
8734 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008735 }
8736
8737 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008738 synchronized (mPidsSelfLocked) {
8739 boolean printed = false;
8740 for (int i=0; i<mForegroundProcesses.size(); i++) {
8741 ProcessRecord r = mPidsSelfLocked.get(
8742 mForegroundProcesses.valueAt(i).pid);
8743 if (dumpPackage != null && (r == null
8744 || !dumpPackage.equals(r.info.packageName))) {
8745 continue;
8746 }
8747 if (!printed) {
8748 if (needSep) pw.println(" ");
8749 needSep = true;
8750 pw.println(" Foreground Processes:");
8751 printed = true;
8752 }
8753 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8754 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008757 }
8758
8759 if (mPersistentStartingProcesses.size() > 0) {
8760 if (needSep) pw.println(" ");
8761 needSep = true;
8762 pw.println(" Persisent processes that are starting:");
8763 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008764 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008767 if (mRemovedProcesses.size() > 0) {
8768 if (needSep) pw.println(" ");
8769 needSep = true;
8770 pw.println(" Processes that are being removed:");
8771 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008772 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008773 }
8774
8775 if (mProcessesOnHold.size() > 0) {
8776 if (needSep) pw.println(" ");
8777 needSep = true;
8778 pw.println(" Processes that are on old until the system is ready:");
8779 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008780 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008783 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008784
8785 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008786 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008787 long now = SystemClock.uptimeMillis();
8788 for (Map.Entry<String, SparseArray<Long>> procs
8789 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008790 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008791 SparseArray<Long> uids = procs.getValue();
8792 final int N = uids.size();
8793 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008794 int puid = uids.keyAt(i);
8795 ProcessRecord r = mProcessNames.get(pname, puid);
8796 if (dumpPackage != null && (r == null
8797 || !dumpPackage.equals(r.info.packageName))) {
8798 continue;
8799 }
8800 if (!printed) {
8801 if (needSep) pw.println(" ");
8802 needSep = true;
8803 pw.println(" Time since processes crashed:");
8804 printed = true;
8805 }
8806 pw.print(" Process "); pw.print(pname);
8807 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008809 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8810 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008811 }
8812 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008814
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008815 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008816 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008817 for (Map.Entry<String, SparseArray<Long>> procs
8818 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008819 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008820 SparseArray<Long> uids = procs.getValue();
8821 final int N = uids.size();
8822 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008823 int puid = uids.keyAt(i);
8824 ProcessRecord r = mProcessNames.get(pname, puid);
8825 if (dumpPackage != null && (r == null
8826 || !dumpPackage.equals(r.info.packageName))) {
8827 continue;
8828 }
8829 if (!printed) {
8830 if (needSep) pw.println(" ");
8831 needSep = true;
8832 pw.println(" Bad processes:");
8833 }
8834 pw.print(" Bad process "); pw.print(pname);
8835 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008836 pw.print(": crashed at time ");
8837 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008838 }
8839 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008841
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008842 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008843 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008844 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008845 if (dumpAll) {
8846 StringBuilder sb = new StringBuilder(128);
8847 sb.append(" mPreviousProcessVisibleTime: ");
8848 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8849 pw.println(sb);
8850 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008851 if (mHeavyWeightProcess != null) {
8852 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8853 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008854 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008855 if (dumpAll) {
8856 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008857 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008858 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008859 for (Map.Entry<String, Integer> entry
8860 : mCompatModePackages.getPackages().entrySet()) {
8861 String pkg = entry.getKey();
8862 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008863 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8864 continue;
8865 }
8866 if (!printed) {
8867 pw.println(" mScreenCompatPackages:");
8868 printed = true;
8869 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008870 pw.print(" "); pw.print(pkg); pw.print(": ");
8871 pw.print(mode); pw.println();
8872 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008873 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008874 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008875 if (mSleeping || mWentToSleep || mLockScreenShown) {
8876 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8877 + " mLockScreenShown " + mLockScreenShown);
8878 }
8879 if (mShuttingDown) {
8880 pw.println(" mShuttingDown=" + mShuttingDown);
8881 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008882 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8883 || mOrigWaitForDebugger) {
8884 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8885 + " mDebugTransient=" + mDebugTransient
8886 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8887 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008888 if (mOpenGlTraceApp != null) {
8889 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8890 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008891 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8892 || mProfileFd != null) {
8893 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8894 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8895 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8896 + mAutoStopProfiler);
8897 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 if (mAlwaysFinishActivities || mController != null) {
8899 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8900 + " mController=" + mController);
8901 }
8902 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008905 + " mProcessesReady=" + mProcessesReady
8906 + " mSystemReady=" + mSystemReady);
8907 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 + " mBooted=" + mBooted
8909 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008910 pw.print(" mLastPowerCheckRealtime=");
8911 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8912 pw.println("");
8913 pw.print(" mLastPowerCheckUptime=");
8914 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8915 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008916 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8917 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008918 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008919 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8920 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008922
8923 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 }
8925
Dianne Hackborn287952c2010-09-22 22:34:31 -07008926 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008927 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008928 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008929 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008930 long now = SystemClock.uptimeMillis();
8931 for (int i=0; i<mProcessesToGc.size(); i++) {
8932 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008933 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8934 continue;
8935 }
8936 if (!printed) {
8937 if (needSep) pw.println(" ");
8938 needSep = true;
8939 pw.println(" Processes that are waiting to GC:");
8940 printed = true;
8941 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008942 pw.print(" Process "); pw.println(proc);
8943 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8944 pw.print(", last gced=");
8945 pw.print(now-proc.lastRequestedGc);
8946 pw.print(" ms ago, last lowMem=");
8947 pw.print(now-proc.lastLowMemory);
8948 pw.println(" ms ago");
8949
8950 }
8951 }
8952 return needSep;
8953 }
8954
8955 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8956 int opti, boolean dumpAll) {
8957 boolean needSep = false;
8958
8959 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008960 if (needSep) pw.println(" ");
8961 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008962 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008963 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008964 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008965 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8966 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8967 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8968 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8969 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008970 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008971 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008972 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008973 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008974 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008975 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008976
8977 if (needSep) pw.println(" ");
8978 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008979 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008980 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008981 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008982 needSep = true;
8983 }
8984
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008985 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008986
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008987 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008988 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008989 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008990 if (mHeavyWeightProcess != null) {
8991 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8992 }
8993
8994 return true;
8995 }
8996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 /**
8998 * There are three ways to call this:
8999 * - no service specified: dump all the services
9000 * - a flattened component name that matched an existing service was specified as the
9001 * first arg: dump that one service
9002 * - the first arg isn't the flattened component name of an existing service:
9003 * dump all services whose component contains the first arg as a substring
9004 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009005 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9006 int opti, boolean dumpAll) {
9007 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009009 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009010 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009011 try {
9012 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9013 for (UserInfo user : users) {
9014 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9015 services.add(r1);
9016 }
9017 }
9018 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009019 }
9020 }
9021 } else {
9022 ComponentName componentName = name != null
9023 ? ComponentName.unflattenFromString(name) : null;
9024 int objectId = 0;
9025 if (componentName == null) {
9026 // Not a '/' separated full component name; maybe an object ID?
9027 try {
9028 objectId = Integer.parseInt(name, 16);
9029 name = null;
9030 componentName = null;
9031 } catch (RuntimeException e) {
9032 }
9033 }
9034
9035 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009036 try {
9037 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9038 for (UserInfo user : users) {
9039 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9040 if (componentName != null) {
9041 if (r1.name.equals(componentName)) {
9042 services.add(r1);
9043 }
9044 } else if (name != null) {
9045 if (r1.name.flattenToString().contains(name)) {
9046 services.add(r1);
9047 }
9048 } else if (System.identityHashCode(r1) == objectId) {
9049 services.add(r1);
9050 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009051 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009052 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009053 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 }
9055 }
9056 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057
9058 if (services.size() <= 0) {
9059 return false;
9060 }
9061
9062 boolean needSep = false;
9063 for (int i=0; i<services.size(); i++) {
9064 if (needSep) {
9065 pw.println();
9066 }
9067 needSep = true;
9068 dumpService("", fd, pw, services.get(i), args, dumpAll);
9069 }
9070 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 }
9072
9073 /**
9074 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9075 * there is a thread associated with the service.
9076 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009077 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9078 final ServiceRecord r, String[] args, boolean dumpAll) {
9079 String innerPrefix = prefix + " ";
9080 synchronized (this) {
9081 pw.print(prefix); pw.print("SERVICE ");
9082 pw.print(r.shortName); pw.print(" ");
9083 pw.print(Integer.toHexString(System.identityHashCode(r)));
9084 pw.print(" pid=");
9085 if (r.app != null) pw.println(r.app.pid);
9086 else pw.println("(not running)");
9087 if (dumpAll) {
9088 r.dump(pw, innerPrefix);
9089 }
9090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009092 pw.print(prefix); pw.println(" Client:");
9093 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009095 TransferPipe tp = new TransferPipe();
9096 try {
9097 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9098 tp.setBufferPrefix(prefix + " ");
9099 tp.go(fd);
9100 } finally {
9101 tp.kill();
9102 }
9103 } catch (IOException e) {
9104 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009105 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009106 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 }
9108 }
9109 }
9110
Marco Nelissen18cb2872011-11-15 11:19:53 -08009111 /**
9112 * There are three ways to call this:
9113 * - no provider specified: dump all the providers
9114 * - a flattened component name that matched an existing provider was specified as the
9115 * first arg: dump that one provider
9116 * - the first arg isn't the flattened component name of an existing provider:
9117 * dump all providers whose component contains the first arg as a substring
9118 */
9119 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9120 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009121 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009122 }
9123
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009124 static class ItemMatcher {
9125 ArrayList<ComponentName> components;
9126 ArrayList<String> strings;
9127 ArrayList<Integer> objects;
9128 boolean all;
9129
9130 ItemMatcher() {
9131 all = true;
9132 }
9133
9134 void build(String name) {
9135 ComponentName componentName = ComponentName.unflattenFromString(name);
9136 if (componentName != null) {
9137 if (components == null) {
9138 components = new ArrayList<ComponentName>();
9139 }
9140 components.add(componentName);
9141 all = false;
9142 } else {
9143 int objectId = 0;
9144 // Not a '/' separated full component name; maybe an object ID?
9145 try {
9146 objectId = Integer.parseInt(name, 16);
9147 if (objects == null) {
9148 objects = new ArrayList<Integer>();
9149 }
9150 objects.add(objectId);
9151 all = false;
9152 } catch (RuntimeException e) {
9153 // Not an integer; just do string match.
9154 if (strings == null) {
9155 strings = new ArrayList<String>();
9156 }
9157 strings.add(name);
9158 all = false;
9159 }
9160 }
9161 }
9162
9163 int build(String[] args, int opti) {
9164 for (; opti<args.length; opti++) {
9165 String name = args[opti];
9166 if ("--".equals(name)) {
9167 return opti+1;
9168 }
9169 build(name);
9170 }
9171 return opti;
9172 }
9173
9174 boolean match(Object object, ComponentName comp) {
9175 if (all) {
9176 return true;
9177 }
9178 if (components != null) {
9179 for (int i=0; i<components.size(); i++) {
9180 if (components.get(i).equals(comp)) {
9181 return true;
9182 }
9183 }
9184 }
9185 if (objects != null) {
9186 for (int i=0; i<objects.size(); i++) {
9187 if (System.identityHashCode(object) == objects.get(i)) {
9188 return true;
9189 }
9190 }
9191 }
9192 if (strings != null) {
9193 String flat = comp.flattenToString();
9194 for (int i=0; i<strings.size(); i++) {
9195 if (flat.contains(strings.get(i))) {
9196 return true;
9197 }
9198 }
9199 }
9200 return false;
9201 }
9202 }
9203
Dianne Hackborn625ac272010-09-17 18:29:22 -07009204 /**
9205 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009206 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009207 * - the cmd arg isn't the flattened component name of an existing activity:
9208 * dump all activity whose component contains the cmd as a substring
9209 * - A hex number of the ActivityRecord object instance.
9210 */
9211 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9212 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009213 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009214
9215 if ("all".equals(name)) {
9216 synchronized (this) {
9217 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009218 activities.add(r1);
9219 }
9220 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009221 } else if ("top".equals(name)) {
9222 synchronized (this) {
9223 final int N = mMainStack.mHistory.size();
9224 if (N > 0) {
9225 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9226 }
9227 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009228 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009229 ItemMatcher matcher = new ItemMatcher();
9230 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009231
9232 synchronized (this) {
9233 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009234 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009235 activities.add(r1);
9236 }
9237 }
9238 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009239 }
9240
9241 if (activities.size() <= 0) {
9242 return false;
9243 }
9244
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009245 String[] newArgs = new String[args.length - opti];
9246 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9247
Dianne Hackborn30d71892010-12-11 10:37:55 -08009248 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009249 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009250 for (int i=activities.size()-1; i>=0; i--) {
9251 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009252 if (needSep) {
9253 pw.println();
9254 }
9255 needSep = true;
9256 synchronized (this) {
9257 if (lastTask != r.task) {
9258 lastTask = r.task;
9259 pw.print("TASK "); pw.print(lastTask.affinity);
9260 pw.print(" id="); pw.println(lastTask.taskId);
9261 if (dumpAll) {
9262 lastTask.dump(pw, " ");
9263 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009264 }
9265 }
9266 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009267 }
9268 return true;
9269 }
9270
9271 /**
9272 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9273 * there is a thread associated with the activity.
9274 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009275 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009276 final ActivityRecord r, String[] args, boolean dumpAll) {
9277 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009278 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009279 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9280 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9281 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009282 if (r.app != null) pw.println(r.app.pid);
9283 else pw.println("(not running)");
9284 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009285 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009286 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009287 }
9288 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009289 // flush anything that is already in the PrintWriter since the thread is going
9290 // to write to the file descriptor directly
9291 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009292 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009293 TransferPipe tp = new TransferPipe();
9294 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009295 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9296 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009297 tp.go(fd);
9298 } finally {
9299 tp.kill();
9300 }
9301 } catch (IOException e) {
9302 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009303 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009304 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009305 }
9306 }
9307 }
9308
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 boolean needSep = false;
9312
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009313 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009314 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009316 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 Iterator it = mRegisteredReceivers.values().iterator();
9318 while (it.hasNext()) {
9319 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009320 if (dumpPackage != null && (r.app == null ||
9321 !dumpPackage.equals(r.app.info.packageName))) {
9322 continue;
9323 }
9324 if (!printed) {
9325 pw.println(" Registered Receivers:");
9326 needSep = true;
9327 printed = true;
9328 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009329 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330 r.dump(pw, " ");
9331 }
9332 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009333
9334 if (mReceiverResolver.dump(pw, needSep ?
9335 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9336 " ", dumpPackage, false)) {
9337 needSep = true;
9338 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009339 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009340
9341 for (BroadcastQueue q : mBroadcastQueues) {
9342 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009345 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009346
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009347 if (mStickyBroadcasts != null && dumpPackage == null) {
9348 if (needSep) {
9349 pw.println();
9350 }
9351 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009352 pw.println(" Sticky broadcasts:");
9353 StringBuilder sb = new StringBuilder(128);
9354 for (Map.Entry<String, ArrayList<Intent>> ent
9355 : mStickyBroadcasts.entrySet()) {
9356 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009357 if (dumpAll) {
9358 pw.println(":");
9359 ArrayList<Intent> intents = ent.getValue();
9360 final int N = intents.size();
9361 for (int i=0; i<N; i++) {
9362 sb.setLength(0);
9363 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009364 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009365 pw.println(sb.toString());
9366 Bundle bundle = intents.get(i).getExtras();
9367 if (bundle != null) {
9368 pw.print(" ");
9369 pw.println(bundle.toString());
9370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009371 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009372 } else {
9373 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009374 }
9375 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009376 needSep = true;
9377 }
9378
9379 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009380 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009381 for (BroadcastQueue queue : mBroadcastQueues) {
9382 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9383 + queue.mBroadcastsScheduled);
9384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 pw.println(" mHandler:");
9386 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009387 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009388 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009389
9390 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 }
9392
Marco Nelissen18cb2872011-11-15 11:19:53 -08009393 /**
9394 * Prints a list of ServiceRecords (dumpsys activity services)
9395 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009396 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009397 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009398 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009399
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009400 ItemMatcher matcher = new ItemMatcher();
9401 matcher.build(args, opti);
9402
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009403 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009404 try {
9405 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9406 for (UserInfo user : users) {
9407 if (mServiceMap.getAllServices(user.id).size() > 0) {
9408 boolean printed = false;
9409 long nowReal = SystemClock.elapsedRealtime();
9410 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9411 user.id).iterator();
9412 needSep = false;
9413 while (it.hasNext()) {
9414 ServiceRecord r = it.next();
9415 if (!matcher.match(r, r.name)) {
9416 continue;
9417 }
9418 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9419 continue;
9420 }
9421 if (!printed) {
9422 pw.println(" Active services:");
9423 printed = true;
9424 }
9425 if (needSep) {
9426 pw.println();
9427 }
9428 pw.print(" * ");
9429 pw.println(r);
9430 if (dumpAll) {
9431 r.dump(pw, " ");
9432 needSep = true;
9433 } else {
9434 pw.print(" app=");
9435 pw.println(r.app);
9436 pw.print(" created=");
9437 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9438 pw.print(" started=");
9439 pw.print(r.startRequested);
9440 pw.print(" connections=");
9441 pw.println(r.connections.size());
9442 if (r.connections.size() > 0) {
9443 pw.println(" Connections:");
9444 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9445 for (int i = 0; i < clist.size(); i++) {
9446 ConnectionRecord conn = clist.get(i);
9447 pw.print(" ");
9448 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009449 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009450 pw.print(" -> ");
9451 ProcessRecord proc = conn.binding.client;
9452 pw.println(proc != null ? proc.toShortString() : "null");
9453 }
9454 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009455 }
9456 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009457 if (dumpClient && r.app != null && r.app.thread != null) {
9458 pw.println(" Client:");
9459 pw.flush();
9460 try {
9461 TransferPipe tp = new TransferPipe();
9462 try {
9463 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9464 r, args);
9465 tp.setBufferPrefix(" ");
9466 // Short timeout, since blocking here can
9467 // deadlock with the application.
9468 tp.go(fd, 2000);
9469 } finally {
9470 tp.kill();
9471 }
9472 } catch (IOException e) {
9473 pw.println(" Failure while dumping the service: " + e);
9474 } catch (RemoteException e) {
9475 pw.println(" Got a RemoteException while dumping the service");
9476 }
9477 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009478 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009479 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009480 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009482 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009483 } catch (RemoteException re) {
9484
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009487 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009488 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009489 for (int i=0; i<mPendingServices.size(); i++) {
9490 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009491 if (!matcher.match(r, r.name)) {
9492 continue;
9493 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009494 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9495 continue;
9496 }
9497 if (!printed) {
9498 if (needSep) pw.println(" ");
9499 needSep = true;
9500 pw.println(" Pending services:");
9501 printed = true;
9502 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009503 pw.print(" * Pending "); pw.println(r);
9504 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009505 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009506 needSep = true;
9507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009508
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009509 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009510 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009511 for (int i=0; i<mRestartingServices.size(); i++) {
9512 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009513 if (!matcher.match(r, r.name)) {
9514 continue;
9515 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009516 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9517 continue;
9518 }
9519 if (!printed) {
9520 if (needSep) pw.println(" ");
9521 needSep = true;
9522 pw.println(" Restarting services:");
9523 printed = true;
9524 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009525 pw.print(" * Restarting "); pw.println(r);
9526 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009528 needSep = true;
9529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009530
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009531 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009532 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009533 for (int i=0; i<mStoppingServices.size(); i++) {
9534 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009535 if (!matcher.match(r, r.name)) {
9536 continue;
9537 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009538 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9539 continue;
9540 }
9541 if (!printed) {
9542 if (needSep) pw.println(" ");
9543 needSep = true;
9544 pw.println(" Stopping services:");
9545 printed = true;
9546 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009547 pw.print(" * Stopping "); pw.println(r);
9548 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009549 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009550 needSep = true;
9551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009552
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009553 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009554 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009555 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009556 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009557 = mServiceConnections.values().iterator();
9558 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009559 ArrayList<ConnectionRecord> r = it.next();
9560 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009561 ConnectionRecord cr = r.get(i);
9562 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9563 continue;
9564 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009565 if (dumpPackage != null && (cr.binding.client == null
9566 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9567 continue;
9568 }
9569 if (!printed) {
9570 if (needSep) pw.println(" ");
9571 needSep = true;
9572 pw.println(" Connection bindings to services:");
9573 printed = true;
9574 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009575 pw.print(" * "); pw.println(cr);
9576 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009578 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009579 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009580 }
9581 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009582
9583 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009584 }
9585
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009586 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009587 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009588 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009589
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009590 ItemMatcher matcher = new ItemMatcher();
9591 matcher.build(args, opti);
9592
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009593 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009594
9595 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009596
9597 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009598 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009599 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009600 ContentProviderRecord r = mLaunchingProviders.get(i);
9601 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9602 continue;
9603 }
9604 if (!printed) {
9605 if (needSep) pw.println(" ");
9606 needSep = true;
9607 pw.println(" Launching content providers:");
9608 printed = true;
9609 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009610 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009611 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009612 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009613 }
9614
9615 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009616 if (needSep) pw.println();
9617 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009618 pw.println("Granted Uri Permissions:");
9619 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9620 int uid = mGrantedUriPermissions.keyAt(i);
9621 HashMap<Uri, UriPermission> perms
9622 = mGrantedUriPermissions.valueAt(i);
9623 pw.print(" * UID "); pw.print(uid);
9624 pw.println(" holds:");
9625 for (UriPermission perm : perms.values()) {
9626 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009627 if (dumpAll) {
9628 perm.dump(pw, " ");
9629 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009630 }
9631 }
9632 needSep = true;
9633 }
9634
9635 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 }
9637
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009638 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009639 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009640 boolean needSep = false;
9641
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009642 if (mIntentSenderRecords.size() > 0) {
9643 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009644 Iterator<WeakReference<PendingIntentRecord>> it
9645 = mIntentSenderRecords.values().iterator();
9646 while (it.hasNext()) {
9647 WeakReference<PendingIntentRecord> ref = it.next();
9648 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009649 if (dumpPackage != null && (rec == null
9650 || !dumpPackage.equals(rec.key.packageName))) {
9651 continue;
9652 }
9653 if (!printed) {
9654 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9655 printed = true;
9656 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009657 needSep = true;
9658 if (rec != null) {
9659 pw.print(" * "); pw.println(rec);
9660 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009662 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009663 } else {
9664 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 }
9666 }
9667 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009668
9669 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009670 }
9671
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009672 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009673 String prefix, String label, boolean complete, boolean brief, boolean client,
9674 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009675 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009676 boolean needNL = false;
9677 final String innerPrefix = prefix + " ";
9678 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009680 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009681 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9682 continue;
9683 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009684 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009685 if (needNL) {
9686 pw.println(" ");
9687 needNL = false;
9688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 if (lastTask != r.task) {
9690 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009691 pw.print(prefix);
9692 pw.print(full ? "* " : " ");
9693 pw.println(lastTask);
9694 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009695 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009696 } else if (complete) {
9697 // Complete + brief == give a summary. Isn't that obvious?!?
9698 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009699 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009700 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009701 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009703 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009704 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9705 pw.print(" #"); pw.print(i); pw.print(": ");
9706 pw.println(r);
9707 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009708 r.dump(pw, innerPrefix);
9709 } else if (complete) {
9710 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009711 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009712 if (r.app != null) {
9713 pw.print(innerPrefix); pw.println(r.app);
9714 }
9715 }
9716 if (client && r.app != null && r.app.thread != null) {
9717 // flush anything that is already in the PrintWriter since the thread is going
9718 // to write to the file descriptor directly
9719 pw.flush();
9720 try {
9721 TransferPipe tp = new TransferPipe();
9722 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009723 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9724 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009725 // Short timeout, since blocking here can
9726 // deadlock with the application.
9727 tp.go(fd, 2000);
9728 } finally {
9729 tp.kill();
9730 }
9731 } catch (IOException e) {
9732 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9733 } catch (RemoteException e) {
9734 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9735 }
9736 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 }
9739 }
9740
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009741 private static String buildOomTag(String prefix, String space, int val, int base) {
9742 if (val == base) {
9743 if (space == null) return prefix;
9744 return prefix + " ";
9745 }
9746 return prefix + "+" + Integer.toString(val-base);
9747 }
9748
9749 private static final int dumpProcessList(PrintWriter pw,
9750 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009751 String prefix, String normalLabel, String persistentLabel,
9752 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009754 final int N = list.size()-1;
9755 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009757 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9758 continue;
9759 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009760 pw.println(String.format("%s%s #%2d: %s",
9761 prefix, (r.persistent ? persistentLabel : normalLabel),
9762 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009763 if (r.persistent) {
9764 numPers++;
9765 }
9766 }
9767 return numPers;
9768 }
9769
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009770 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009771 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009772 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009773 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009774
Dianne Hackborn905577f2011-09-07 18:31:28 -07009775 ArrayList<Pair<ProcessRecord, Integer>> list
9776 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9777 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009778 ProcessRecord r = origList.get(i);
9779 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9780 continue;
9781 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009782 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9783 }
9784
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009785 if (list.size() <= 0) {
9786 return false;
9787 }
9788
Dianne Hackborn905577f2011-09-07 18:31:28 -07009789 Comparator<Pair<ProcessRecord, Integer>> comparator
9790 = new Comparator<Pair<ProcessRecord, Integer>>() {
9791 @Override
9792 public int compare(Pair<ProcessRecord, Integer> object1,
9793 Pair<ProcessRecord, Integer> object2) {
9794 if (object1.first.setAdj != object2.first.setAdj) {
9795 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9796 }
9797 if (object1.second.intValue() != object2.second.intValue()) {
9798 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9799 }
9800 return 0;
9801 }
9802 };
9803
9804 Collections.sort(list, comparator);
9805
Dianne Hackborn287952c2010-09-22 22:34:31 -07009806 final long curRealtime = SystemClock.elapsedRealtime();
9807 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9808 final long curUptime = SystemClock.uptimeMillis();
9809 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9810
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009811 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009812 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009813 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009814 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009815 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009816 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9817 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009818 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9819 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009820 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9821 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009822 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9823 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009824 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009825 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009826 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9827 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9828 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9829 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9830 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9831 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9832 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9833 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009834 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9835 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009836 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9837 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009838 } else {
9839 oomAdj = Integer.toString(r.setAdj);
9840 }
9841 String schedGroup;
9842 switch (r.setSchedGroup) {
9843 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9844 schedGroup = "B";
9845 break;
9846 case Process.THREAD_GROUP_DEFAULT:
9847 schedGroup = "F";
9848 break;
9849 default:
9850 schedGroup = Integer.toString(r.setSchedGroup);
9851 break;
9852 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009853 String foreground;
9854 if (r.foregroundActivities) {
9855 foreground = "A";
9856 } else if (r.foregroundServices) {
9857 foreground = "S";
9858 } else {
9859 foreground = " ";
9860 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009861 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009862 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009863 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9864 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009865 if (r.adjSource != null || r.adjTarget != null) {
9866 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009867 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009868 if (r.adjTarget instanceof ComponentName) {
9869 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9870 } else if (r.adjTarget != null) {
9871 pw.print(r.adjTarget.toString());
9872 } else {
9873 pw.print("{null}");
9874 }
9875 pw.print("<=");
9876 if (r.adjSource instanceof ProcessRecord) {
9877 pw.print("Proc{");
9878 pw.print(((ProcessRecord)r.adjSource).toShortString());
9879 pw.println("}");
9880 } else if (r.adjSource != null) {
9881 pw.println(r.adjSource.toString());
9882 } else {
9883 pw.println("{null}");
9884 }
9885 }
9886 if (inclDetails) {
9887 pw.print(prefix);
9888 pw.print(" ");
9889 pw.print("oom: max="); pw.print(r.maxAdj);
9890 pw.print(" hidden="); pw.print(r.hiddenAdj);
9891 pw.print(" curRaw="); pw.print(r.curRawAdj);
9892 pw.print(" setRaw="); pw.print(r.setRawAdj);
9893 pw.print(" cur="); pw.print(r.curAdj);
9894 pw.print(" set="); pw.println(r.setAdj);
9895 pw.print(prefix);
9896 pw.print(" ");
9897 pw.print("keeping="); pw.print(r.keeping);
9898 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009899 pw.print(" empty="); pw.print(r.empty);
9900 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009901
9902 if (!r.keeping) {
9903 if (r.lastWakeTime != 0) {
9904 long wtime;
9905 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9906 synchronized (stats) {
9907 wtime = stats.getProcessWakeTime(r.info.uid,
9908 r.pid, curRealtime);
9909 }
9910 long timeUsed = wtime - r.lastWakeTime;
9911 pw.print(prefix);
9912 pw.print(" ");
9913 pw.print("keep awake over ");
9914 TimeUtils.formatDuration(realtimeSince, pw);
9915 pw.print(" used ");
9916 TimeUtils.formatDuration(timeUsed, pw);
9917 pw.print(" (");
9918 pw.print((timeUsed*100)/realtimeSince);
9919 pw.println("%)");
9920 }
9921 if (r.lastCpuTime != 0) {
9922 long timeUsed = r.curCpuTime - r.lastCpuTime;
9923 pw.print(prefix);
9924 pw.print(" ");
9925 pw.print("run cpu over ");
9926 TimeUtils.formatDuration(uptimeSince, pw);
9927 pw.print(" used ");
9928 TimeUtils.formatDuration(timeUsed, pw);
9929 pw.print(" (");
9930 pw.print((timeUsed*100)/uptimeSince);
9931 pw.println("%)");
9932 }
9933 }
9934 }
9935 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009936 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009937 }
9938
Dianne Hackbornb437e092011-08-05 17:50:29 -07009939 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009940 ArrayList<ProcessRecord> procs;
9941 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009942 if (args != null && args.length > start
9943 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009944 procs = new ArrayList<ProcessRecord>();
9945 int pid = -1;
9946 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009947 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009948 } catch (NumberFormatException e) {
9949
9950 }
9951 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9952 ProcessRecord proc = mLruProcesses.get(i);
9953 if (proc.pid == pid) {
9954 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009955 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009956 procs.add(proc);
9957 }
9958 }
9959 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009960 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009961 return null;
9962 }
9963 } else {
9964 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9965 }
9966 }
9967 return procs;
9968 }
9969
9970 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9971 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009972 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009973 if (procs == null) {
9974 return;
9975 }
9976
9977 long uptime = SystemClock.uptimeMillis();
9978 long realtime = SystemClock.elapsedRealtime();
9979 pw.println("Applications Graphics Acceleration Info:");
9980 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9981
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009982 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9983 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009984 if (r.thread != null) {
9985 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9986 pw.flush();
9987 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009988 TransferPipe tp = new TransferPipe();
9989 try {
9990 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9991 tp.go(fd);
9992 } finally {
9993 tp.kill();
9994 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009995 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009996 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009997 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009998 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009999 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010000 pw.flush();
10001 }
10002 }
10003 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010004 }
10005
Jeff Brown6754ba22011-12-14 20:20:01 -080010006 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10007 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10008 if (procs == null) {
10009 return;
10010 }
10011
10012 pw.println("Applications Database Info:");
10013
10014 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10015 ProcessRecord r = procs.get(i);
10016 if (r.thread != null) {
10017 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10018 pw.flush();
10019 try {
10020 TransferPipe tp = new TransferPipe();
10021 try {
10022 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10023 tp.go(fd);
10024 } finally {
10025 tp.kill();
10026 }
10027 } catch (IOException e) {
10028 pw.println("Failure while dumping the app: " + r);
10029 pw.flush();
10030 } catch (RemoteException e) {
10031 pw.println("Got a RemoteException while dumping the app " + r);
10032 pw.flush();
10033 }
10034 }
10035 }
10036 }
10037
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010038 final static class MemItem {
10039 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010040 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010041 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010042 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010043 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010044
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010045 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010046 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010047 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010048 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010049 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010050 }
10051 }
10052
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010053 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010054 boolean sort) {
10055 if (sort) {
10056 Collections.sort(items, new Comparator<MemItem>() {
10057 @Override
10058 public int compare(MemItem lhs, MemItem rhs) {
10059 if (lhs.pss < rhs.pss) {
10060 return 1;
10061 } else if (lhs.pss > rhs.pss) {
10062 return -1;
10063 }
10064 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010065 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010066 });
10067 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010068
10069 for (int i=0; i<items.size(); i++) {
10070 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010071 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010072 if (mi.subitems != null) {
10073 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10074 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010075 }
10076 }
10077
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010078 // These are in KB.
10079 static final long[] DUMP_MEM_BUCKETS = new long[] {
10080 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10081 120*1024, 160*1024, 200*1024,
10082 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10083 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10084 };
10085
Dianne Hackborn672342c2011-11-29 11:29:02 -080010086 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10087 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010088 int start = label.lastIndexOf('.');
10089 if (start >= 0) start++;
10090 else start = 0;
10091 int end = label.length();
10092 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10093 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10094 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10095 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010096 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010097 out.append(label, start, end);
10098 return;
10099 }
10100 }
10101 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010102 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010103 out.append(label, start, end);
10104 }
10105
10106 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10107 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10108 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10109 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10110 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10111 };
10112 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10113 "System", "Persistent", "Foreground",
10114 "Visible", "Perceptible", "Heavy Weight",
10115 "Backup", "A Services", "Home", "Previous",
10116 "B Services", "Background"
10117 };
10118
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010119 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010120 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010121 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010122 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010123 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010124
10125 int opti = 0;
10126 while (opti < args.length) {
10127 String opt = args[opti];
10128 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10129 break;
10130 }
10131 opti++;
10132 if ("-a".equals(opt)) {
10133 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010134 } else if ("--oom".equals(opt)) {
10135 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010136 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010137 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010138 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010139 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010140 pw.println("If [process] is specified it can be the name or ");
10141 pw.println("pid of a specific process to dump.");
10142 return;
10143 } else {
10144 pw.println("Unknown argument: " + opt + "; use -h for help");
10145 }
10146 }
10147
10148 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010149 if (procs == null) {
10150 return;
10151 }
10152
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010153 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010154 long uptime = SystemClock.uptimeMillis();
10155 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010156
10157 if (procs.size() == 1 || isCheckinRequest) {
10158 dumpAll = true;
10159 }
10160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010161 if (isCheckinRequest) {
10162 // short checkin version
10163 pw.println(uptime + "," + realtime);
10164 pw.flush();
10165 } else {
10166 pw.println("Applications Memory Usage (kB):");
10167 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10168 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010169
Dianne Hackbornb437e092011-08-05 17:50:29 -070010170 String[] innerArgs = new String[args.length-opti];
10171 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10172
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010173 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10174 long nativePss=0, dalvikPss=0, otherPss=0;
10175 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10176
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010177 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10178 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10179 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010180
10181 long totalPss = 0;
10182
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010183 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10184 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010186 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010187 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10188 pw.flush();
10189 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010190 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010191 if (dumpAll) {
10192 try {
10193 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10194 } catch (RemoteException e) {
10195 if (!isCheckinRequest) {
10196 pw.println("Got RemoteException!");
10197 pw.flush();
10198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010199 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200 } else {
10201 mi = new Debug.MemoryInfo();
10202 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010203 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010204
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010205 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010206 long myTotalPss = mi.getTotalPss();
10207 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010208 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010209 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010210 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010211
10212 nativePss += mi.nativePss;
10213 dalvikPss += mi.dalvikPss;
10214 otherPss += mi.otherPss;
10215 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10216 long mem = mi.getOtherPss(j);
10217 miscPss[j] += mem;
10218 otherPss -= mem;
10219 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010220
10221 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010222 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10223 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010224 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010225 if (oomProcs[oomIndex] == null) {
10226 oomProcs[oomIndex] = new ArrayList<MemItem>();
10227 }
10228 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010229 break;
10230 }
10231 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010233 }
10234 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010235
10236 if (!isCheckinRequest && procs.size() > 1) {
10237 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10238
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010239 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10240 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10241 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010242 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010243 String label = Debug.MemoryInfo.getOtherLabel(j);
10244 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010245 }
10246
Dianne Hackbornb437e092011-08-05 17:50:29 -070010247 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10248 for (int j=0; j<oomPss.length; j++) {
10249 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010250 String label = DUMP_MEM_OOM_LABEL[j];
10251 MemItem item = new MemItem(label, label, oomPss[j],
10252 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010253 item.subitems = oomProcs[j];
10254 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010255 }
10256 }
10257
Dianne Hackborn672342c2011-11-29 11:29:02 -080010258 if (outTag != null || outStack != null) {
10259 if (outTag != null) {
10260 appendMemBucket(outTag, totalPss, "total", false);
10261 }
10262 if (outStack != null) {
10263 appendMemBucket(outStack, totalPss, "total", true);
10264 }
10265 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010266 for (int i=0; i<oomMems.size(); i++) {
10267 MemItem miCat = oomMems.get(i);
10268 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10269 continue;
10270 }
10271 if (miCat.id < ProcessList.SERVICE_ADJ
10272 || miCat.id == ProcessList.HOME_APP_ADJ
10273 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010274 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10275 outTag.append(" / ");
10276 }
10277 if (outStack != null) {
10278 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10279 if (firstLine) {
10280 outStack.append(":");
10281 firstLine = false;
10282 }
10283 outStack.append("\n\t at ");
10284 } else {
10285 outStack.append("$");
10286 }
10287 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010288 for (int j=0; j<miCat.subitems.size(); j++) {
10289 MemItem mi = miCat.subitems.get(j);
10290 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010291 if (outTag != null) {
10292 outTag.append(" ");
10293 }
10294 if (outStack != null) {
10295 outStack.append("$");
10296 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010297 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010298 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10299 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10300 }
10301 if (outStack != null) {
10302 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10303 }
10304 }
10305 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10306 outStack.append("(");
10307 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10308 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10309 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10310 outStack.append(":");
10311 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10312 }
10313 }
10314 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010315 }
10316 }
10317 }
10318 }
10319
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010320 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010321 pw.println();
10322 pw.println("Total PSS by process:");
10323 dumpMemItems(pw, " ", procMems, true);
10324 pw.println();
10325 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010326 pw.println("Total PSS by OOM adjustment:");
10327 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010328 if (!oomOnly) {
10329 PrintWriter out = categoryPw != null ? categoryPw : pw;
10330 out.println();
10331 out.println("Total PSS by category:");
10332 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010333 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010334 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010335 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010336 final int[] SINGLE_LONG_FORMAT = new int[] {
10337 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10338 };
10339 long[] longOut = new long[1];
10340 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10341 SINGLE_LONG_FORMAT, null, longOut, null);
10342 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10343 longOut[0] = 0;
10344 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10345 SINGLE_LONG_FORMAT, null, longOut, null);
10346 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10347 longOut[0] = 0;
10348 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10349 SINGLE_LONG_FORMAT, null, longOut, null);
10350 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10351 longOut[0] = 0;
10352 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10353 SINGLE_LONG_FORMAT, null, longOut, null);
10354 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10355 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10356 pw.print(shared); pw.println(" kB");
10357 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10358 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010360 }
10361
10362 /**
10363 * Searches array of arguments for the specified string
10364 * @param args array of argument strings
10365 * @param value value to search for
10366 * @return true if the value is contained in the array
10367 */
10368 private static boolean scanArgs(String[] args, String value) {
10369 if (args != null) {
10370 for (String arg : args) {
10371 if (value.equals(arg)) {
10372 return true;
10373 }
10374 }
10375 }
10376 return false;
10377 }
10378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010379 private final void killServicesLocked(ProcessRecord app,
10380 boolean allowRestart) {
10381 // Report disconnected services.
10382 if (false) {
10383 // XXX we are letting the client link to the service for
10384 // death notifications.
10385 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010386 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010387 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010388 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010389 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010390 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010391 = r.connections.values().iterator();
10392 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010393 ArrayList<ConnectionRecord> cl = jt.next();
10394 for (int i=0; i<cl.size(); i++) {
10395 ConnectionRecord c = cl.get(i);
10396 if (c.binding.client != app) {
10397 try {
10398 //c.conn.connected(r.className, null);
10399 } catch (Exception e) {
10400 // todo: this should be asynchronous!
10401 Slog.w(TAG, "Exception thrown disconnected servce "
10402 + r.shortName
10403 + " from app " + app.processName, e);
10404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010405 }
10406 }
10407 }
10408 }
10409 }
10410 }
10411 }
10412
10413 // Clean up any connections this application has to other services.
10414 if (app.connections.size() > 0) {
10415 Iterator<ConnectionRecord> it = app.connections.iterator();
10416 while (it.hasNext()) {
10417 ConnectionRecord r = it.next();
10418 removeConnectionLocked(r, app, null);
10419 }
10420 }
10421 app.connections.clear();
10422
10423 if (app.services.size() != 0) {
10424 // Any services running in the application need to be placed
10425 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010426 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010427 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010428 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429 synchronized (sr.stats.getBatteryStats()) {
10430 sr.stats.stopLaunchedLocked();
10431 }
10432 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010433 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010434 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010435 if (mStoppingServices.remove(sr)) {
10436 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10437 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010438
10439 boolean hasClients = sr.bindings.size() > 0;
10440 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010441 Iterator<IntentBindRecord> bindings
10442 = sr.bindings.values().iterator();
10443 while (bindings.hasNext()) {
10444 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010445 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010446 + ": shouldUnbind=" + b.hasBound);
10447 b.binder = null;
10448 b.requested = b.received = b.hasBound = false;
10449 }
10450 }
10451
Dianne Hackborn070783f2010-12-29 16:46:28 -080010452 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10453 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010454 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010455 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010456 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457 sr.crashCount, sr.shortName, app.pid);
10458 bringDownServiceLocked(sr, true);
10459 } else if (!allowRestart) {
10460 bringDownServiceLocked(sr, true);
10461 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010462 boolean canceled = scheduleServiceRestartLocked(sr, true);
10463
10464 // Should the service remain running? Note that in the
10465 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010466 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010467 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10468 if (sr.pendingStarts.size() == 0) {
10469 sr.startRequested = false;
10470 if (!hasClients) {
10471 // Whoops, no reason to restart!
10472 bringDownServiceLocked(sr, true);
10473 }
10474 }
10475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010476 }
10477 }
10478
10479 if (!allowRestart) {
10480 app.services.clear();
10481 }
10482 }
10483
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010484 // Make sure we have no more records on the stopping list.
10485 int i = mStoppingServices.size();
10486 while (i > 0) {
10487 i--;
10488 ServiceRecord sr = mStoppingServices.get(i);
10489 if (sr.app == app) {
10490 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010491 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010492 }
10493 }
10494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010495 app.executingServices.clear();
10496 }
10497
10498 private final void removeDyingProviderLocked(ProcessRecord proc,
10499 ContentProviderRecord cpr) {
10500 synchronized (cpr) {
10501 cpr.launchingApp = null;
10502 cpr.notifyAll();
10503 }
10504
Amith Yamasani742a6712011-05-04 14:49:28 -070010505 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010506 String names[] = cpr.info.authority.split(";");
10507 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010508 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 }
10510
10511 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10512 while (cit.hasNext()) {
10513 ProcessRecord capp = cit.next();
10514 if (!capp.persistent && capp.thread != null
10515 && capp.pid != 0
10516 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010517 Slog.i(TAG, "Kill " + capp.processName
10518 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010519 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010520 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010521 capp.processName, capp.setAdj, "dying provider "
10522 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010523 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010524 }
10525 }
10526
10527 mLaunchingProviders.remove(cpr);
10528 }
10529
10530 /**
10531 * Main code for cleaning up a process when it has gone away. This is
10532 * called both as a result of the process dying, or directly when stopping
10533 * a process when running in single process mode.
10534 */
10535 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010536 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010537 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010538 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010539 }
10540
Dianne Hackborn36124872009-10-08 16:22:03 -070010541 mProcessesToGc.remove(app);
10542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010543 // Dismiss any open dialogs.
10544 if (app.crashDialog != null) {
10545 app.crashDialog.dismiss();
10546 app.crashDialog = null;
10547 }
10548 if (app.anrDialog != null) {
10549 app.anrDialog.dismiss();
10550 app.anrDialog = null;
10551 }
10552 if (app.waitDialog != null) {
10553 app.waitDialog.dismiss();
10554 app.waitDialog = null;
10555 }
10556
10557 app.crashing = false;
10558 app.notResponding = false;
10559
10560 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010561 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 app.thread = null;
10563 app.forcingToForeground = null;
10564 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010565 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010566 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010567 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010568
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010569 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570
10571 boolean restart = false;
10572
10573 int NL = mLaunchingProviders.size();
10574
10575 // Remove published content providers.
10576 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010577 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010579 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010581 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582
10583 // See if someone is waiting for this provider... in which
10584 // case we don't remove it, but just let it restart.
10585 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010586 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010587 for (; i<NL; i++) {
10588 if (mLaunchingProviders.get(i) == cpr) {
10589 restart = true;
10590 break;
10591 }
10592 }
10593 } else {
10594 i = NL;
10595 }
10596
10597 if (i >= NL) {
10598 removeDyingProviderLocked(app, cpr);
10599 NL = mLaunchingProviders.size();
10600 }
10601 }
10602 app.pubProviders.clear();
10603 }
10604
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010605 // Take care of any launching providers waiting for this process.
10606 if (checkAppInLaunchingProvidersLocked(app, false)) {
10607 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010610 // Unregister from connected content providers.
10611 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010612 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613 while (it.hasNext()) {
10614 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10615 cpr.clients.remove(app);
10616 }
10617 app.conProviders.clear();
10618 }
10619
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010620 // At this point there may be remaining entries in mLaunchingProviders
10621 // where we were the only one waiting, so they are no longer of use.
10622 // Look for these and clean up if found.
10623 // XXX Commented out for now. Trying to figure out a way to reproduce
10624 // the actual situation to identify what is actually going on.
10625 if (false) {
10626 for (int i=0; i<NL; i++) {
10627 ContentProviderRecord cpr = (ContentProviderRecord)
10628 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010629 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010630 synchronized (cpr) {
10631 cpr.launchingApp = null;
10632 cpr.notifyAll();
10633 }
10634 }
10635 }
10636 }
10637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010638 skipCurrentReceiverLocked(app);
10639
10640 // Unregister any receivers.
10641 if (app.receivers.size() > 0) {
10642 Iterator<ReceiverList> it = app.receivers.iterator();
10643 while (it.hasNext()) {
10644 removeReceiverLocked(it.next());
10645 }
10646 app.receivers.clear();
10647 }
10648
Christopher Tate181fafa2009-05-14 11:12:14 -070010649 // If the app is undergoing backup, tell the backup manager about it
10650 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010651 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010652 try {
10653 IBackupManager bm = IBackupManager.Stub.asInterface(
10654 ServiceManager.getService(Context.BACKUP_SERVICE));
10655 bm.agentDisconnected(app.info.packageName);
10656 } catch (RemoteException e) {
10657 // can't happen; backup manager is local
10658 }
10659 }
10660
Jeff Sharkey287bd832011-05-28 19:36:26 -070010661 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 // If the caller is restarting this app, then leave it in its
10664 // current lists and let the caller take care of it.
10665 if (restarting) {
10666 return;
10667 }
10668
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010669 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010670 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010671 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010672 mProcessNames.remove(app.processName, app.uid);
10673 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010674 if (mHeavyWeightProcess == app) {
10675 mHeavyWeightProcess = null;
10676 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010678 } else if (!app.removed) {
10679 // This app is persistent, so we need to keep its record around.
10680 // If it is not already on the pending app list, add it there
10681 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010682 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10683 mPersistentStartingProcesses.add(app);
10684 restart = true;
10685 }
10686 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010687 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10688 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 mProcessesOnHold.remove(app);
10690
The Android Open Source Project4df24232009-03-05 14:34:35 -080010691 if (app == mHomeProcess) {
10692 mHomeProcess = null;
10693 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010694 if (app == mPreviousProcess) {
10695 mPreviousProcess = null;
10696 }
10697
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010698 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 // We have components that still need to be running in the
10700 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010701 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010702 startProcessLocked(app, "restart", app.processName);
10703 } else if (app.pid > 0 && app.pid != MY_PID) {
10704 // Goodbye!
10705 synchronized (mPidsSelfLocked) {
10706 mPidsSelfLocked.remove(app.pid);
10707 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10708 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010709 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010710 }
10711 }
10712
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010713 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10714 // Look through the content providers we are waiting to have launched,
10715 // and if any run in this process then either schedule a restart of
10716 // the process or kill the client waiting for it if this process has
10717 // gone bad.
10718 int NL = mLaunchingProviders.size();
10719 boolean restart = false;
10720 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010721 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010722 if (cpr.launchingApp == app) {
10723 if (!alwaysBad && !app.bad) {
10724 restart = true;
10725 } else {
10726 removeDyingProviderLocked(app, cpr);
10727 NL = mLaunchingProviders.size();
10728 }
10729 }
10730 }
10731 return restart;
10732 }
10733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 // =========================================================
10735 // SERVICES
10736 // =========================================================
10737
10738 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10739 ActivityManager.RunningServiceInfo info =
10740 new ActivityManager.RunningServiceInfo();
10741 info.service = r.name;
10742 if (r.app != null) {
10743 info.pid = r.app.pid;
10744 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010745 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 info.process = r.processName;
10747 info.foreground = r.isForeground;
10748 info.activeSince = r.createTime;
10749 info.started = r.startRequested;
10750 info.clientCount = r.connections.size();
10751 info.crashCount = r.crashCount;
10752 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010753 if (r.isForeground) {
10754 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10755 }
10756 if (r.startRequested) {
10757 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10758 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010759 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010760 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10761 }
10762 if (r.app != null && r.app.persistent) {
10763 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10764 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010765
10766 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10767 for (int i=0; i<connl.size(); i++) {
10768 ConnectionRecord conn = connl.get(i);
10769 if (conn.clientLabel != 0) {
10770 info.clientPackage = conn.binding.client.info.packageName;
10771 info.clientLabel = conn.clientLabel;
10772 return info;
10773 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010774 }
10775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 return info;
10777 }
10778
10779 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10780 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010781 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010782 synchronized (this) {
10783 ArrayList<ActivityManager.RunningServiceInfo> res
10784 = new ArrayList<ActivityManager.RunningServiceInfo>();
10785
Amith Yamasani742a6712011-05-04 14:49:28 -070010786 int userId = UserId.getUserId(Binder.getCallingUid());
10787 if (mServiceMap.getAllServices(userId).size() > 0) {
10788 Iterator<ServiceRecord> it
10789 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010790 while (it.hasNext() && res.size() < maxNum) {
10791 res.add(makeRunningServiceInfoLocked(it.next()));
10792 }
10793 }
10794
10795 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10796 ServiceRecord r = mRestartingServices.get(i);
10797 ActivityManager.RunningServiceInfo info =
10798 makeRunningServiceInfoLocked(r);
10799 info.restarting = r.nextRestartTime;
10800 res.add(info);
10801 }
10802
10803 return res;
10804 }
10805 }
10806
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010807 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010808 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010809 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010810 int userId = UserId.getUserId(Binder.getCallingUid());
10811 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010812 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010813 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10814 for (int i=0; i<conn.size(); i++) {
10815 if (conn.get(i).clientIntent != null) {
10816 return conn.get(i).clientIntent;
10817 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010818 }
10819 }
10820 }
10821 }
10822 return null;
10823 }
10824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 private final ServiceRecord findServiceLocked(ComponentName name,
10826 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010827 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010828 return r == token ? r : null;
10829 }
10830
10831 private final class ServiceLookupResult {
10832 final ServiceRecord record;
10833 final String permission;
10834
10835 ServiceLookupResult(ServiceRecord _record, String _permission) {
10836 record = _record;
10837 permission = _permission;
10838 }
10839 };
10840
10841 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010842 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010843 ServiceRecord r = null;
10844 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010845 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010846 }
10847 if (r == null) {
10848 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010849 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010850 }
10851
10852 if (r == null) {
10853 try {
10854 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010855 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010856 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 ServiceInfo sInfo =
10858 rInfo != null ? rInfo.serviceInfo : null;
10859 if (sInfo == null) {
10860 return null;
10861 }
10862
10863 ComponentName name = new ComponentName(
10864 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010865 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 } catch (RemoteException ex) {
10867 // pm is in same process, this will never happen.
10868 }
10869 }
10870 if (r != null) {
10871 int callingPid = Binder.getCallingPid();
10872 int callingUid = Binder.getCallingUid();
10873 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010874 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010876 if (!r.exported) {
10877 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10878 + " from pid=" + callingPid
10879 + ", uid=" + callingUid
10880 + " that is not exported from uid " + r.appInfo.uid);
10881 return new ServiceLookupResult(null, "not exported from uid "
10882 + r.appInfo.uid);
10883 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010884 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010885 + " from pid=" + callingPid
10886 + ", uid=" + callingUid
10887 + " requires " + r.permission);
10888 return new ServiceLookupResult(null, r.permission);
10889 }
10890 return new ServiceLookupResult(r, null);
10891 }
10892 return null;
10893 }
10894
10895 private class ServiceRestarter implements Runnable {
10896 private ServiceRecord mService;
10897
10898 void setService(ServiceRecord service) {
10899 mService = service;
10900 }
10901
10902 public void run() {
10903 synchronized(ActivityManagerService.this) {
10904 performServiceRestartLocked(mService);
10905 }
10906 }
10907 }
10908
10909 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010910 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010911 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010912 if (DEBUG_SERVICE)
10913 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010914 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010917 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010918 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010919 if (r == null) {
10920 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010921 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 if (r == null) {
10924 try {
10925 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010926 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010927 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 ServiceInfo sInfo =
10929 rInfo != null ? rInfo.serviceInfo : null;
10930 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010931 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010932 ": not found");
10933 return null;
10934 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010935 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010936 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10937 userId = 0;
10938 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010939 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941 ComponentName name = new ComponentName(
10942 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010943 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010945 Intent.FilterComparison filter = new Intent.FilterComparison(
10946 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010947 ServiceRestarter res = new ServiceRestarter();
10948 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10949 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10950 synchronized (stats) {
10951 ss = stats.getServiceStatsLocked(
10952 sInfo.applicationInfo.uid, sInfo.packageName,
10953 sInfo.name);
10954 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010955 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010957 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10958 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959
10960 // Make sure this component isn't in the pending list.
10961 int N = mPendingServices.size();
10962 for (int i=0; i<N; i++) {
10963 ServiceRecord pr = mPendingServices.get(i);
10964 if (pr.name.equals(name)) {
10965 mPendingServices.remove(i);
10966 i--;
10967 N--;
10968 }
10969 }
10970 }
10971 } catch (RemoteException ex) {
10972 // pm is in same process, this will never happen.
10973 }
10974 }
10975 if (r != null) {
10976 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010977 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010978 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010979 if (!r.exported) {
10980 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10981 + " from pid=" + callingPid
10982 + ", uid=" + callingUid
10983 + " that is not exported from uid " + r.appInfo.uid);
10984 return new ServiceLookupResult(null, "not exported from uid "
10985 + r.appInfo.uid);
10986 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010987 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010988 + " from pid=" + callingPid
10989 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990 + " requires " + r.permission);
10991 return new ServiceLookupResult(null, r.permission);
10992 }
10993 return new ServiceLookupResult(r, null);
10994 }
10995 return null;
10996 }
10997
Dianne Hackborn287952c2010-09-22 22:34:31 -070010998 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10999 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11000 + why + " of " + r + " in app " + r.app);
11001 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11002 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 long now = SystemClock.uptimeMillis();
11004 if (r.executeNesting == 0 && r.app != null) {
11005 if (r.app.executingServices.size() == 0) {
11006 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11007 msg.obj = r.app;
11008 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11009 }
11010 r.app.executingServices.add(r);
11011 }
11012 r.executeNesting++;
11013 r.executingStart = now;
11014 }
11015
11016 private final void sendServiceArgsLocked(ServiceRecord r,
11017 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011018 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011019 if (N == 0) {
11020 return;
11021 }
11022
Dianne Hackborn39792d22010-08-19 18:01:52 -070011023 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011024 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011025 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011026 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11027 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011028 if (si.intent == null && N > 1) {
11029 // If somehow we got a dummy null intent in the middle,
11030 // then skip it. DO NOT skip a null intent when it is
11031 // the only one in the list -- this is to support the
11032 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011033 continue;
11034 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011035 si.deliveredTime = SystemClock.uptimeMillis();
11036 r.deliveredStarts.add(si);
11037 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011038 if (si.neededGrants != null) {
11039 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11040 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011041 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011042 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011043 if (!oomAdjusted) {
11044 oomAdjusted = true;
11045 updateOomAdjLocked(r.app);
11046 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011047 int flags = 0;
11048 if (si.deliveryCount > 0) {
11049 flags |= Service.START_FLAG_RETRY;
11050 }
11051 if (si.doneExecutingCount > 0) {
11052 flags |= Service.START_FLAG_REDELIVERY;
11053 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011054 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011055 } catch (RemoteException e) {
11056 // Remote process gone... we'll let the normal cleanup take
11057 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011058 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011059 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011060 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011061 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011062 break;
11063 }
11064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011065 }
11066
11067 private final boolean requestServiceBindingLocked(ServiceRecord r,
11068 IntentBindRecord i, boolean rebind) {
11069 if (r.app == null || r.app.thread == null) {
11070 // If service is not currently running, can't yet bind.
11071 return false;
11072 }
11073 if ((!i.requested || rebind) && i.apps.size() > 0) {
11074 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011075 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011076 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11077 if (!rebind) {
11078 i.requested = true;
11079 }
11080 i.hasBound = true;
11081 i.doRebind = false;
11082 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011083 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 return false;
11085 }
11086 }
11087 return true;
11088 }
11089
11090 private final void requestServiceBindingsLocked(ServiceRecord r) {
11091 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11092 while (bindings.hasNext()) {
11093 IntentBindRecord i = bindings.next();
11094 if (!requestServiceBindingLocked(r, i, false)) {
11095 break;
11096 }
11097 }
11098 }
11099
11100 private final void realStartServiceLocked(ServiceRecord r,
11101 ProcessRecord app) throws RemoteException {
11102 if (app.thread == null) {
11103 throw new RemoteException();
11104 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011105 if (DEBUG_MU)
11106 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011107 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011108 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011109 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110
11111 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011112 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011113 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114
11115 boolean created = false;
11116 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011117 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011118 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011119 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011120 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011121 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 synchronized (r.stats.getBatteryStats()) {
11123 r.stats.startLaunchedLocked();
11124 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011125 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011126 app.thread.scheduleCreateService(r, r.serviceInfo,
11127 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011128 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011129 created = true;
11130 } finally {
11131 if (!created) {
11132 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011133 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011134 }
11135 }
11136
11137 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011138
11139 // If the service is in the started state, and there are no
11140 // pending arguments, then fake up one so its onStartCommand() will
11141 // be called.
11142 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011143 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011144 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011145 }
11146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147 sendServiceArgsLocked(r, true);
11148 }
11149
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011150 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11151 boolean allowCancel) {
11152 boolean canceled = false;
11153
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011154 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011155 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011156 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011157
Dianne Hackborn070783f2010-12-29 16:46:28 -080011158 if ((r.serviceInfo.applicationInfo.flags
11159 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11160 minDuration /= 4;
11161 }
11162
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011163 // Any delivered but not yet finished starts should be put back
11164 // on the pending list.
11165 final int N = r.deliveredStarts.size();
11166 if (N > 0) {
11167 for (int i=N-1; i>=0; i--) {
11168 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011169 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011170 if (si.intent == null) {
11171 // We'll generate this again if needed.
11172 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11173 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11174 r.pendingStarts.add(0, si);
11175 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11176 dur *= 2;
11177 if (minDuration < dur) minDuration = dur;
11178 if (resetTime < dur) resetTime = dur;
11179 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011180 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011181 + r.name);
11182 canceled = true;
11183 }
11184 }
11185 r.deliveredStarts.clear();
11186 }
11187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 r.totalRestartCount++;
11189 if (r.restartDelay == 0) {
11190 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011191 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011192 } else {
11193 // If it has been a "reasonably long time" since the service
11194 // was started, then reset our restart duration back to
11195 // the beginning, so we don't infinitely increase the duration
11196 // on a service that just occasionally gets killed (which is
11197 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011198 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011199 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011200 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011202 if ((r.serviceInfo.applicationInfo.flags
11203 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11204 // Services in peristent processes will restart much more
11205 // quickly, since they are pretty important. (Think SystemUI).
11206 r.restartDelay += minDuration/2;
11207 } else {
11208 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11209 if (r.restartDelay < minDuration) {
11210 r.restartDelay = minDuration;
11211 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 }
11214 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011215
11216 r.nextRestartTime = now + r.restartDelay;
11217
11218 // Make sure that we don't end up restarting a bunch of services
11219 // all at the same time.
11220 boolean repeat;
11221 do {
11222 repeat = false;
11223 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11224 ServiceRecord r2 = mRestartingServices.get(i);
11225 if (r2 != r && r.nextRestartTime
11226 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11227 && r.nextRestartTime
11228 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11229 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11230 r.restartDelay = r.nextRestartTime - now;
11231 repeat = true;
11232 break;
11233 }
11234 }
11235 } while (repeat);
11236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 if (!mRestartingServices.contains(r)) {
11238 mRestartingServices.add(r);
11239 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011240
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011241 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011244 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011246 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011247 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011248 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249 r.shortName, r.restartDelay);
11250
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011251 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 }
11253
11254 final void performServiceRestartLocked(ServiceRecord r) {
11255 if (!mRestartingServices.contains(r)) {
11256 return;
11257 }
11258 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11259 }
11260
11261 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11262 if (r.restartDelay == 0) {
11263 return false;
11264 }
11265 r.resetRestartCounter();
11266 mRestartingServices.remove(r);
11267 mHandler.removeCallbacks(r.restarter);
11268 return true;
11269 }
11270
11271 private final boolean bringUpServiceLocked(ServiceRecord r,
11272 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011273 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 //r.dump(" ");
11275
Dianne Hackborn36124872009-10-08 16:22:03 -070011276 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011277 sendServiceArgsLocked(r, false);
11278 return true;
11279 }
11280
11281 if (!whileRestarting && r.restartDelay > 0) {
11282 // If waiting for a restart, then do nothing.
11283 return true;
11284 }
11285
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011286 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011288 // We are now bringing the service up, so no longer in the
11289 // restarting state.
11290 mRestartingServices.remove(r);
11291
Dianne Hackborne7f97212011-02-24 14:40:20 -080011292 // Service is now being launched, its package can't be stopped.
11293 try {
11294 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011295 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011296 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011297 } catch (IllegalArgumentException e) {
11298 Slog.w(TAG, "Failed trying to unstop package "
11299 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011300 }
11301
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011302 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011303 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011304 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011306 if (!isolated) {
11307 app = getProcessRecordLocked(appName, r.appInfo.uid);
11308 if (DEBUG_MU)
11309 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11310 if (app != null && app.thread != null) {
11311 try {
11312 app.addPackage(r.appInfo.packageName);
11313 realStartServiceLocked(r, app);
11314 return true;
11315 } catch (RemoteException e) {
11316 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11317 }
11318
11319 // If a dead object exception was thrown -- fall through to
11320 // restart the application.
11321 }
11322 } else {
11323 // If this service runs in an isolated process, then each time
11324 // we call startProcessLocked() we will get a new isolated
11325 // process, starting another process if we are currently waiting
11326 // for a previous process to come up. To deal with this, we store
11327 // in the service any current isolated process it is running in or
11328 // waiting to have come up.
11329 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330 }
11331
Dianne Hackborn36124872009-10-08 16:22:03 -070011332 // Not running -- get it started, and enqueue this service record
11333 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011334 if (app == null) {
11335 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11336 "service", r.name, false, isolated)) == null) {
11337 Slog.w(TAG, "Unable to launch app "
11338 + r.appInfo.packageName + "/"
11339 + r.appInfo.uid + " for service "
11340 + r.intent.getIntent() + ": process is bad");
11341 bringDownServiceLocked(r, true);
11342 return false;
11343 }
11344 if (isolated) {
11345 r.isolatedProc = app;
11346 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011347 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011349 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 mPendingServices.add(r);
11351 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011353 return true;
11354 }
11355
11356 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011357 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 //r.dump(" ");
11359
11360 // Does it still need to run?
11361 if (!force && r.startRequested) {
11362 return;
11363 }
11364 if (r.connections.size() > 0) {
11365 if (!force) {
11366 // XXX should probably keep a count of the number of auto-create
11367 // connections directly in the service.
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> cr = it.next();
11371 for (int i=0; i<cr.size(); i++) {
11372 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11373 return;
11374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375 }
11376 }
11377 }
11378
11379 // Report to all of the connections that the service is no longer
11380 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011381 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011383 ArrayList<ConnectionRecord> c = it.next();
11384 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011385 ConnectionRecord cr = c.get(i);
11386 // There is still a connection to the service that is
11387 // being brought down. Mark it as dead.
11388 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011389 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011390 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011391 } catch (Exception e) {
11392 Slog.w(TAG, "Failure disconnecting service " + r.name +
11393 " to connection " + c.get(i).conn.asBinder() +
11394 " (in " + c.get(i).binding.client.processName + ")", e);
11395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 }
11397 }
11398 }
11399
11400 // Tell the service that it has been unbound.
11401 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11402 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11403 while (it.hasNext()) {
11404 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011405 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011406 + ": hasBound=" + ibr.hasBound);
11407 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11408 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011409 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011410 updateOomAdjLocked(r.app);
11411 ibr.hasBound = false;
11412 r.app.thread.scheduleUnbindService(r,
11413 ibr.intent.getIntent());
11414 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011415 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 + r.shortName, e);
11417 serviceDoneExecutingLocked(r, true);
11418 }
11419 }
11420 }
11421 }
11422
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011423 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011424 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011425 System.identityHashCode(r), r.shortName,
11426 (r.app != null) ? r.app.pid : -1);
11427
Amith Yamasani742a6712011-05-04 14:49:28 -070011428 mServiceMap.removeServiceByName(r.name, r.userId);
11429 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011430 r.totalRestartCount = 0;
11431 unscheduleServiceRestartLocked(r);
11432
11433 // Also make sure it is not on the pending list.
11434 int N = mPendingServices.size();
11435 for (int i=0; i<N; i++) {
11436 if (mPendingServices.get(i) == r) {
11437 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011438 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011439 i--;
11440 N--;
11441 }
11442 }
11443
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011444 r.cancelNotification();
11445 r.isForeground = false;
11446 r.foregroundId = 0;
11447 r.foregroundNoti = null;
11448
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011449 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011450 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011451 r.pendingStarts.clear();
11452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 if (r.app != null) {
11454 synchronized (r.stats.getBatteryStats()) {
11455 r.stats.stopLaunchedLocked();
11456 }
11457 r.app.services.remove(r);
11458 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011459 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011460 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 mStoppingServices.add(r);
11462 updateOomAdjLocked(r.app);
11463 r.app.thread.scheduleStopService(r);
11464 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011465 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011466 + r.shortName, e);
11467 serviceDoneExecutingLocked(r, true);
11468 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011469 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011471 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011472 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 }
11474 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011475 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011476 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011478
11479 if (r.bindings.size() > 0) {
11480 r.bindings.clear();
11481 }
11482
11483 if (r.restarter instanceof ServiceRestarter) {
11484 ((ServiceRestarter)r.restarter).setService(null);
11485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 }
11487
11488 ComponentName startServiceLocked(IApplicationThread caller,
11489 Intent service, String resolvedType,
11490 int callingPid, int callingUid) {
11491 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011492 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 + " type=" + resolvedType + " args=" + service.getExtras());
11494
11495 if (caller != null) {
11496 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11497 if (callerApp == null) {
11498 throw new SecurityException(
11499 "Unable to find app for caller " + caller
11500 + " (pid=" + Binder.getCallingPid()
11501 + ") when starting service " + service);
11502 }
11503 }
11504
11505 ServiceLookupResult res =
11506 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011507 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011508 if (res == null) {
11509 return null;
11510 }
11511 if (res.record == null) {
11512 return new ComponentName("!", res.permission != null
11513 ? res.permission : "private to package");
11514 }
11515 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011516 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11517 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011519 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011520 }
11521 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011522 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011523 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011524 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011525 r.lastActivity = SystemClock.uptimeMillis();
11526 synchronized (r.stats.getBatteryStats()) {
11527 r.stats.startRunningLocked();
11528 }
11529 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11530 return new ComponentName("!", "Service process is bad");
11531 }
11532 return r.name;
11533 }
11534 }
11535
11536 public ComponentName startService(IApplicationThread caller, Intent service,
11537 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011538 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 // Refuse possible leaked file descriptors
11540 if (service != null && service.hasFileDescriptors() == true) {
11541 throw new IllegalArgumentException("File descriptors passed in Intent");
11542 }
11543
Amith Yamasani742a6712011-05-04 14:49:28 -070011544 if (DEBUG_SERVICE)
11545 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 synchronized(this) {
11547 final int callingPid = Binder.getCallingPid();
11548 final int callingUid = Binder.getCallingUid();
11549 final long origId = Binder.clearCallingIdentity();
11550 ComponentName res = startServiceLocked(caller, service,
11551 resolvedType, callingPid, callingUid);
11552 Binder.restoreCallingIdentity(origId);
11553 return res;
11554 }
11555 }
11556
11557 ComponentName startServiceInPackage(int uid,
11558 Intent service, String resolvedType) {
11559 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011560 if (DEBUG_SERVICE)
11561 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 final long origId = Binder.clearCallingIdentity();
11563 ComponentName res = startServiceLocked(null, service,
11564 resolvedType, -1, uid);
11565 Binder.restoreCallingIdentity(origId);
11566 return res;
11567 }
11568 }
11569
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011570 private void stopServiceLocked(ServiceRecord service) {
11571 synchronized (service.stats.getBatteryStats()) {
11572 service.stats.stopRunningLocked();
11573 }
11574 service.startRequested = false;
11575 service.callStart = false;
11576 bringDownServiceLocked(service, false);
11577 }
11578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011579 public int stopService(IApplicationThread caller, Intent service,
11580 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011581 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 // Refuse possible leaked file descriptors
11583 if (service != null && service.hasFileDescriptors() == true) {
11584 throw new IllegalArgumentException("File descriptors passed in Intent");
11585 }
11586
11587 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011588 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589 + " type=" + resolvedType);
11590
11591 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11592 if (caller != null && callerApp == null) {
11593 throw new SecurityException(
11594 "Unable to find app for caller " + caller
11595 + " (pid=" + Binder.getCallingPid()
11596 + ") when stopping service " + service);
11597 }
11598
11599 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011600 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11601 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011602 if (r != null) {
11603 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011605 try {
11606 stopServiceLocked(r.record);
11607 } finally {
11608 Binder.restoreCallingIdentity(origId);
11609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 return 1;
11611 }
11612 return -1;
11613 }
11614 }
11615
11616 return 0;
11617 }
11618
11619 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011620 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621 // Refuse possible leaked file descriptors
11622 if (service != null && service.hasFileDescriptors() == true) {
11623 throw new IllegalArgumentException("File descriptors passed in Intent");
11624 }
11625
11626 IBinder ret = null;
11627
11628 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011629 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11630 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011631
11632 if (r != null) {
11633 // r.record is null if findServiceLocked() failed the caller permission check
11634 if (r.record == null) {
11635 throw new SecurityException(
11636 "Permission Denial: Accessing service " + r.record.name
11637 + " from pid=" + Binder.getCallingPid()
11638 + ", uid=" + Binder.getCallingUid()
11639 + " requires " + r.permission);
11640 }
11641 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11642 if (ib != null) {
11643 ret = ib.binder;
11644 }
11645 }
11646 }
11647
11648 return ret;
11649 }
11650
11651 public boolean stopServiceToken(ComponentName className, IBinder token,
11652 int startId) {
11653 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011654 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 + " " + token + " startId=" + startId);
11656 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011657 if (r != null) {
11658 if (startId >= 0) {
11659 // Asked to only stop if done with all work. Note that
11660 // to avoid leaks, we will take this as dropping all
11661 // start items up to and including this one.
11662 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11663 if (si != null) {
11664 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011665 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11666 cur.removeUriPermissionsLocked();
11667 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011668 break;
11669 }
11670 }
11671 }
11672
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011673 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011674 return false;
11675 }
11676
11677 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011678 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011679 + " is last, but have " + r.deliveredStarts.size()
11680 + " remaining args");
11681 }
11682 }
11683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 synchronized (r.stats.getBatteryStats()) {
11685 r.stats.stopRunningLocked();
11686 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011687 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011688 }
11689 final long origId = Binder.clearCallingIdentity();
11690 bringDownServiceLocked(r, false);
11691 Binder.restoreCallingIdentity(origId);
11692 return true;
11693 }
11694 }
11695 return false;
11696 }
11697
11698 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011699 int id, Notification notification, boolean removeNotification) {
11700 final long origId = Binder.clearCallingIdentity();
11701 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011702 synchronized(this) {
11703 ServiceRecord r = findServiceLocked(className, token);
11704 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011705 if (id != 0) {
11706 if (notification == null) {
11707 throw new IllegalArgumentException("null notification");
11708 }
11709 if (r.foregroundId != id) {
11710 r.cancelNotification();
11711 r.foregroundId = id;
11712 }
11713 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11714 r.foregroundNoti = notification;
11715 r.isForeground = true;
11716 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 if (r.app != null) {
11718 updateServiceForegroundLocked(r.app, true);
11719 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011720 } else {
11721 if (r.isForeground) {
11722 r.isForeground = false;
11723 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011724 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011725 updateServiceForegroundLocked(r.app, true);
11726 }
11727 }
11728 if (removeNotification) {
11729 r.cancelNotification();
11730 r.foregroundId = 0;
11731 r.foregroundNoti = null;
11732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011733 }
11734 }
11735 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011736 } finally {
11737 Binder.restoreCallingIdentity(origId);
11738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739 }
11740
11741 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11742 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011743 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 if (sr.isForeground) {
11745 anyForeground = true;
11746 break;
11747 }
11748 }
11749 if (anyForeground != proc.foregroundServices) {
11750 proc.foregroundServices = anyForeground;
11751 if (oomAdj) {
11752 updateOomAdjLocked();
11753 }
11754 }
11755 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011756
11757 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11758 boolean result = false;
11759 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11760 result = false;
11761 } else if (componentProcessName == aInfo.packageName) {
11762 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11763 } else if ("system".equals(componentProcessName)) {
11764 result = true;
11765 }
11766 if (DEBUG_MU) {
11767 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11768 }
11769 return result;
11770 }
11771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011772 public int bindService(IApplicationThread caller, IBinder token,
11773 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011774 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011775 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 // Refuse possible leaked file descriptors
11777 if (service != null && service.hasFileDescriptors() == true) {
11778 throw new IllegalArgumentException("File descriptors passed in Intent");
11779 }
11780
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011781 checkValidCaller(Binder.getCallingUid(), userId);
11782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011783 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011784 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011785 + " type=" + resolvedType + " conn=" + connection.asBinder()
11786 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011787 if (DEBUG_MU)
11788 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11789 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011790 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11791 if (callerApp == null) {
11792 throw new SecurityException(
11793 "Unable to find app for caller " + caller
11794 + " (pid=" + Binder.getCallingPid()
11795 + ") when binding service " + service);
11796 }
11797
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011798 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011800 activity = mMainStack.isInStackLocked(token);
11801 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011802 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 return 0;
11804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 }
11806
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011807 int clientLabel = 0;
11808 PendingIntent clientIntent = null;
11809
11810 if (callerApp.info.uid == Process.SYSTEM_UID) {
11811 // Hacky kind of thing -- allow system stuff to tell us
11812 // what they are, so we can report this elsewhere for
11813 // others to know why certain services are running.
11814 try {
11815 clientIntent = (PendingIntent)service.getParcelableExtra(
11816 Intent.EXTRA_CLIENT_INTENT);
11817 } catch (RuntimeException e) {
11818 }
11819 if (clientIntent != null) {
11820 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11821 if (clientLabel != 0) {
11822 // There are no useful extras in the intent, trash them.
11823 // System code calling with this stuff just needs to know
11824 // this will happen.
11825 service = service.cloneFilter();
11826 }
11827 }
11828 }
11829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 ServiceLookupResult res =
11831 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011832 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011833 if (res == null) {
11834 return 0;
11835 }
11836 if (res.record == null) {
11837 return -1;
11838 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011839 if (isSingleton(res.record.processName, res.record.appInfo)) {
11840 userId = 0;
11841 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11842 Binder.getCallingUid(), 0);
11843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011844 ServiceRecord s = res.record;
11845
11846 final long origId = Binder.clearCallingIdentity();
11847
11848 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011849 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011850 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011851 }
11852
11853 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11854 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011855 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856
11857 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011858 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11859 if (clist == null) {
11860 clist = new ArrayList<ConnectionRecord>();
11861 s.connections.put(binder, clist);
11862 }
11863 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 b.connections.add(c);
11865 if (activity != null) {
11866 if (activity.connections == null) {
11867 activity.connections = new HashSet<ConnectionRecord>();
11868 }
11869 activity.connections.add(c);
11870 }
11871 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011872 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11873 b.client.hasAboveClient = true;
11874 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011875 clist = mServiceConnections.get(binder);
11876 if (clist == null) {
11877 clist = new ArrayList<ConnectionRecord>();
11878 mServiceConnections.put(binder, clist);
11879 }
11880 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881
11882 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11883 s.lastActivity = SystemClock.uptimeMillis();
11884 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11885 return 0;
11886 }
11887 }
11888
11889 if (s.app != null) {
11890 // This could have made the service more important.
11891 updateOomAdjLocked(s.app);
11892 }
11893
Joe Onorato8a9b2202010-02-26 18:56:32 -080011894 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011895 + ": received=" + b.intent.received
11896 + " apps=" + b.intent.apps.size()
11897 + " doRebind=" + b.intent.doRebind);
11898
11899 if (s.app != null && b.intent.received) {
11900 // Service is already running, so we can immediately
11901 // publish the connection.
11902 try {
11903 c.conn.connected(s.name, b.intent.binder);
11904 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011905 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011906 + " to connection " + c.conn.asBinder()
11907 + " (in " + c.binding.client.processName + ")", e);
11908 }
11909
11910 // If this is the first app connected back to this binding,
11911 // and the service had previously asked to be told when
11912 // rebound, then do so.
11913 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11914 requestServiceBindingLocked(s, b.intent, true);
11915 }
11916 } else if (!b.intent.requested) {
11917 requestServiceBindingLocked(s, b.intent, false);
11918 }
11919
11920 Binder.restoreCallingIdentity(origId);
11921 }
11922
11923 return 1;
11924 }
11925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011926 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011927 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011928 IBinder binder = c.conn.asBinder();
11929 AppBindRecord b = c.binding;
11930 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011931 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11932 if (clist != null) {
11933 clist.remove(c);
11934 if (clist.size() == 0) {
11935 s.connections.remove(binder);
11936 }
11937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011938 b.connections.remove(c);
11939 if (c.activity != null && c.activity != skipAct) {
11940 if (c.activity.connections != null) {
11941 c.activity.connections.remove(c);
11942 }
11943 }
11944 if (b.client != skipApp) {
11945 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011946 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11947 b.client.updateHasAboveClientLocked();
11948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011950 clist = mServiceConnections.get(binder);
11951 if (clist != null) {
11952 clist.remove(c);
11953 if (clist.size() == 0) {
11954 mServiceConnections.remove(binder);
11955 }
11956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957
11958 if (b.connections.size() == 0) {
11959 b.intent.apps.remove(b.client);
11960 }
11961
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011962 if (!c.serviceDead) {
11963 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11964 + ": shouldUnbind=" + b.intent.hasBound);
11965 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11966 && b.intent.hasBound) {
11967 try {
11968 bumpServiceExecutingLocked(s, "unbind");
11969 updateOomAdjLocked(s.app);
11970 b.intent.hasBound = false;
11971 // Assume the client doesn't want to know about a rebind;
11972 // we will deal with that later if it asks for one.
11973 b.intent.doRebind = false;
11974 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11975 } catch (Exception e) {
11976 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11977 serviceDoneExecutingLocked(s, true);
11978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011980
11981 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11982 bringDownServiceLocked(s, false);
11983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 }
11985 }
11986
11987 public boolean unbindService(IServiceConnection connection) {
11988 synchronized (this) {
11989 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011990 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011991 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11992 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011993 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011994 + connection.asBinder());
11995 return false;
11996 }
11997
11998 final long origId = Binder.clearCallingIdentity();
11999
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012000 while (clist.size() > 0) {
12001 ConnectionRecord r = clist.get(0);
12002 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012004 if (r.binding.service.app != null) {
12005 // This could have made the service less important.
12006 updateOomAdjLocked(r.binding.service.app);
12007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012008 }
12009
12010 Binder.restoreCallingIdentity(origId);
12011 }
12012
12013 return true;
12014 }
12015
12016 public void publishService(IBinder token, Intent intent, IBinder service) {
12017 // Refuse possible leaked file descriptors
12018 if (intent != null && intent.hasFileDescriptors() == true) {
12019 throw new IllegalArgumentException("File descriptors passed in Intent");
12020 }
12021
12022 synchronized(this) {
12023 if (!(token instanceof ServiceRecord)) {
12024 throw new IllegalArgumentException("Invalid service token");
12025 }
12026 ServiceRecord r = (ServiceRecord)token;
12027
12028 final long origId = Binder.clearCallingIdentity();
12029
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012030 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012031 + " " + intent + ": " + service);
12032 if (r != null) {
12033 Intent.FilterComparison filter
12034 = new Intent.FilterComparison(intent);
12035 IntentBindRecord b = r.bindings.get(filter);
12036 if (b != null && !b.received) {
12037 b.binder = service;
12038 b.requested = true;
12039 b.received = true;
12040 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012041 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012042 = r.connections.values().iterator();
12043 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012044 ArrayList<ConnectionRecord> clist = it.next();
12045 for (int i=0; i<clist.size(); i++) {
12046 ConnectionRecord c = clist.get(i);
12047 if (!filter.equals(c.binding.intent.intent)) {
12048 if (DEBUG_SERVICE) Slog.v(
12049 TAG, "Not publishing to: " + c);
12050 if (DEBUG_SERVICE) Slog.v(
12051 TAG, "Bound intent: " + c.binding.intent.intent);
12052 if (DEBUG_SERVICE) Slog.v(
12053 TAG, "Published intent: " + intent);
12054 continue;
12055 }
12056 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12057 try {
12058 c.conn.connected(r.name, service);
12059 } catch (Exception e) {
12060 Slog.w(TAG, "Failure sending service " + r.name +
12061 " to connection " + c.conn.asBinder() +
12062 " (in " + c.binding.client.processName + ")", e);
12063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012064 }
12065 }
12066 }
12067 }
12068
12069 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12070
12071 Binder.restoreCallingIdentity(origId);
12072 }
12073 }
12074 }
12075
12076 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12077 // Refuse possible leaked file descriptors
12078 if (intent != null && intent.hasFileDescriptors() == true) {
12079 throw new IllegalArgumentException("File descriptors passed in Intent");
12080 }
12081
12082 synchronized(this) {
12083 if (!(token instanceof ServiceRecord)) {
12084 throw new IllegalArgumentException("Invalid service token");
12085 }
12086 ServiceRecord r = (ServiceRecord)token;
12087
12088 final long origId = Binder.clearCallingIdentity();
12089
12090 if (r != null) {
12091 Intent.FilterComparison filter
12092 = new Intent.FilterComparison(intent);
12093 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012094 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 + " at " + b + ": apps="
12096 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012097
12098 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012099 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012100 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 // Applications have already bound since the last
12102 // unbind, so just rebind right here.
12103 requestServiceBindingLocked(r, b, true);
12104 } else {
12105 // Note to tell the service the next time there is
12106 // a new client.
12107 b.doRebind = true;
12108 }
12109 }
12110
Per Edelberg78f9fff2010-08-30 20:01:35 +020012111 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112
12113 Binder.restoreCallingIdentity(origId);
12114 }
12115 }
12116 }
12117
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012118 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012119 synchronized(this) {
12120 if (!(token instanceof ServiceRecord)) {
12121 throw new IllegalArgumentException("Invalid service token");
12122 }
12123 ServiceRecord r = (ServiceRecord)token;
12124 boolean inStopping = mStoppingServices.contains(token);
12125 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012127 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 + " with incorrect token: given " + token
12129 + ", expected " + r);
12130 return;
12131 }
12132
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012133 if (type == 1) {
12134 // This is a call from a service start... take care of
12135 // book-keeping.
12136 r.callStart = true;
12137 switch (res) {
12138 case Service.START_STICKY_COMPATIBILITY:
12139 case Service.START_STICKY: {
12140 // We are done with the associated start arguments.
12141 r.findDeliveredStart(startId, true);
12142 // Don't stop if killed.
12143 r.stopIfKilled = false;
12144 break;
12145 }
12146 case Service.START_NOT_STICKY: {
12147 // We are done with the associated start arguments.
12148 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012149 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012150 // There is no more work, and this service
12151 // doesn't want to hang around if killed.
12152 r.stopIfKilled = true;
12153 }
12154 break;
12155 }
12156 case Service.START_REDELIVER_INTENT: {
12157 // We'll keep this item until they explicitly
12158 // call stop for it, but keep track of the fact
12159 // that it was delivered.
12160 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12161 if (si != null) {
12162 si.deliveryCount = 0;
12163 si.doneExecutingCount++;
12164 // Don't stop if killed.
12165 r.stopIfKilled = true;
12166 }
12167 break;
12168 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012169 case Service.START_TASK_REMOVED_COMPLETE: {
12170 // Special processing for onTaskRemoved(). Don't
12171 // impact normal onStartCommand() processing.
12172 r.findDeliveredStart(startId, true);
12173 break;
12174 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012175 default:
12176 throw new IllegalArgumentException(
12177 "Unknown service start result: " + res);
12178 }
12179 if (res == Service.START_STICKY_COMPATIBILITY) {
12180 r.callStart = false;
12181 }
12182 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012183 if (DEBUG_MU)
12184 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12185 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 final long origId = Binder.clearCallingIdentity();
12187 serviceDoneExecutingLocked(r, inStopping);
12188 Binder.restoreCallingIdentity(origId);
12189 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012190 Slog.w(TAG, "Done executing unknown service from pid "
12191 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012192 }
12193 }
12194 }
12195
12196 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012197 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12198 + ": nesting=" + r.executeNesting
12199 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012200 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012201 r.executeNesting--;
12202 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012203 if (DEBUG_SERVICE) Slog.v(TAG,
12204 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012205 r.app.executingServices.remove(r);
12206 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012207 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12208 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012209 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12210 }
12211 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012212 if (DEBUG_SERVICE) Slog.v(TAG,
12213 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012214 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012215 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012216 }
12217 updateOomAdjLocked(r.app);
12218 }
12219 }
12220
12221 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012222 String anrMessage = null;
12223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224 synchronized(this) {
12225 if (proc.executingServices.size() == 0 || proc.thread == null) {
12226 return;
12227 }
12228 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12229 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12230 ServiceRecord timeout = null;
12231 long nextTime = 0;
12232 while (it.hasNext()) {
12233 ServiceRecord sr = it.next();
12234 if (sr.executingStart < maxTime) {
12235 timeout = sr;
12236 break;
12237 }
12238 if (sr.executingStart > nextTime) {
12239 nextTime = sr.executingStart;
12240 }
12241 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012242 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012243 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012244 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245 } else {
12246 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12247 msg.obj = proc;
12248 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12249 }
12250 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012251
12252 if (anrMessage != null) {
12253 appNotResponding(proc, null, null, anrMessage);
12254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012255 }
12256
12257 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012258 // BACKUP AND RESTORE
12259 // =========================================================
12260
12261 // Cause the target app to be launched if necessary and its backup agent
12262 // instantiated. The backup agent will invoke backupAgentCreated() on the
12263 // activity manager to announce its creation.
12264 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012265 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012266 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12267
12268 synchronized(this) {
12269 // !!! TODO: currently no check here that we're already bound
12270 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12271 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12272 synchronized (stats) {
12273 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12274 }
12275
Dianne Hackborne7f97212011-02-24 14:40:20 -080012276 // Backup agent is now in use, its package can't be stopped.
12277 try {
12278 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012279 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012280 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012281 } catch (IllegalArgumentException e) {
12282 Slog.w(TAG, "Failed trying to unstop package "
12283 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012284 }
12285
Christopher Tate181fafa2009-05-14 11:12:14 -070012286 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012287 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12288 ? new ComponentName(app.packageName, app.backupAgentName)
12289 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012290 // startProcessLocked() returns existing proc's record if it's already running
12291 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012292 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012293 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012294 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012295 return false;
12296 }
12297
12298 r.app = proc;
12299 mBackupTarget = r;
12300 mBackupAppName = app.packageName;
12301
Christopher Tate6fa95972009-06-05 18:43:55 -070012302 // Try not to kill the process during backup
12303 updateOomAdjLocked(proc);
12304
Christopher Tate181fafa2009-05-14 11:12:14 -070012305 // If the process is already attached, schedule the creation of the backup agent now.
12306 // If it is not yet live, this will be done when it attaches to the framework.
12307 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012308 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012309 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012310 proc.thread.scheduleCreateBackupAgent(app,
12311 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012312 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012313 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012314 }
12315 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012316 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012317 }
12318 // Invariants: at this point, the target app process exists and the application
12319 // is either already running or in the process of coming up. mBackupTarget and
12320 // mBackupAppName describe the app, so that when it binds back to the AM we
12321 // know that it's scheduled for a backup-agent operation.
12322 }
12323
12324 return true;
12325 }
12326
12327 // A backup agent has just come up
12328 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012329 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012330 + " = " + agent);
12331
12332 synchronized(this) {
12333 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012334 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012335 return;
12336 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012337 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012338
Dianne Hackborn06740692010-09-22 22:46:21 -070012339 long oldIdent = Binder.clearCallingIdentity();
12340 try {
12341 IBackupManager bm = IBackupManager.Stub.asInterface(
12342 ServiceManager.getService(Context.BACKUP_SERVICE));
12343 bm.agentConnected(agentPackageName, agent);
12344 } catch (RemoteException e) {
12345 // can't happen; the backup manager service is local
12346 } catch (Exception e) {
12347 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12348 e.printStackTrace();
12349 } finally {
12350 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012351 }
12352 }
12353
12354 // done with this agent
12355 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012356 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012357 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012358 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012359 return;
12360 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012361
12362 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012363 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012364 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012365 return;
12366 }
12367
Christopher Tate181fafa2009-05-14 11:12:14 -070012368 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012369 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012370 return;
12371 }
12372
Christopher Tate6fa95972009-06-05 18:43:55 -070012373 ProcessRecord proc = mBackupTarget.app;
12374 mBackupTarget = null;
12375 mBackupAppName = null;
12376
12377 // Not backing this app up any more; reset its OOM adjustment
12378 updateOomAdjLocked(proc);
12379
Christopher Tatec7b31e32009-06-10 15:49:30 -070012380 // If the app crashed during backup, 'thread' will be null here
12381 if (proc.thread != null) {
12382 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012383 proc.thread.scheduleDestroyBackupAgent(appInfo,
12384 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012385 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012386 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012387 e.printStackTrace();
12388 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012389 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012390 }
12391 }
12392 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012393 // BROADCASTS
12394 // =========================================================
12395
Josh Bartel7f208742010-02-25 11:01:44 -060012396 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012397 List cur) {
12398 final ContentResolver resolver = mContext.getContentResolver();
12399 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12400 if (list == null) {
12401 return cur;
12402 }
12403 int N = list.size();
12404 for (int i=0; i<N; i++) {
12405 Intent intent = list.get(i);
12406 if (filter.match(resolver, intent, true, TAG) >= 0) {
12407 if (cur == null) {
12408 cur = new ArrayList<Intent>();
12409 }
12410 cur.add(intent);
12411 }
12412 }
12413 return cur;
12414 }
12415
Christopher Tatef46723b2012-01-26 14:19:24 -080012416 boolean isPendingBroadcastProcessLocked(int pid) {
12417 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12418 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012420
Christopher Tatef46723b2012-01-26 14:19:24 -080012421 void skipPendingBroadcastLocked(int pid) {
12422 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12423 for (BroadcastQueue queue : mBroadcastQueues) {
12424 queue.skipPendingBroadcastLocked(pid);
12425 }
12426 }
12427
12428 // The app just attached; send any pending broadcasts that it should receive
12429 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12430 boolean didSomething = false;
12431 for (BroadcastQueue queue : mBroadcastQueues) {
12432 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012434 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 }
12436
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012437 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012438 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012439 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440 synchronized(this) {
12441 ProcessRecord callerApp = null;
12442 if (caller != null) {
12443 callerApp = getRecordForAppLocked(caller);
12444 if (callerApp == null) {
12445 throw new SecurityException(
12446 "Unable to find app for caller " + caller
12447 + " (pid=" + Binder.getCallingPid()
12448 + ") when registering receiver " + receiver);
12449 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012450 if (callerApp.info.uid != Process.SYSTEM_UID &&
12451 !callerApp.pkgList.contains(callerPackage)) {
12452 throw new SecurityException("Given caller package " + callerPackage
12453 + " is not running in process " + callerApp);
12454 }
12455 } else {
12456 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012457 }
12458
12459 List allSticky = null;
12460
12461 // Look for any matching sticky broadcasts...
12462 Iterator actions = filter.actionsIterator();
12463 if (actions != null) {
12464 while (actions.hasNext()) {
12465 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012466 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012467 }
12468 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012469 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 }
12471
12472 // The first sticky in the list is returned directly back to
12473 // the client.
12474 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12475
Joe Onorato8a9b2202010-02-26 18:56:32 -080012476 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 + ": " + sticky);
12478
12479 if (receiver == null) {
12480 return sticky;
12481 }
12482
12483 ReceiverList rl
12484 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12485 if (rl == null) {
12486 rl = new ReceiverList(this, callerApp,
12487 Binder.getCallingPid(),
12488 Binder.getCallingUid(), receiver);
12489 if (rl.app != null) {
12490 rl.app.receivers.add(rl);
12491 } else {
12492 try {
12493 receiver.asBinder().linkToDeath(rl, 0);
12494 } catch (RemoteException e) {
12495 return sticky;
12496 }
12497 rl.linkedToDeath = true;
12498 }
12499 mRegisteredReceivers.put(receiver.asBinder(), rl);
12500 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012501 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012502 rl.add(bf);
12503 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012504 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012505 }
12506 mReceiverResolver.addFilter(bf);
12507
12508 // Enqueue broadcasts for all existing stickies that match
12509 // this filter.
12510 if (allSticky != null) {
12511 ArrayList receivers = new ArrayList();
12512 receivers.add(bf);
12513
12514 int N = allSticky.size();
12515 for (int i=0; i<N; i++) {
12516 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012517 BroadcastQueue queue = broadcastQueueForIntent(intent);
12518 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012519 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012520 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012521 queue.enqueueParallelBroadcastLocked(r);
12522 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 }
12524 }
12525
12526 return sticky;
12527 }
12528 }
12529
12530 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012531 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012532
Christopher Tatef46723b2012-01-26 14:19:24 -080012533 final long origId = Binder.clearCallingIdentity();
12534 try {
12535 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012536
Christopher Tatef46723b2012-01-26 14:19:24 -080012537 synchronized(this) {
12538 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012540 if (rl != null) {
12541 if (rl.curBroadcast != null) {
12542 BroadcastRecord r = rl.curBroadcast;
12543 final boolean doNext = finishReceiverLocked(
12544 receiver.asBinder(), r.resultCode, r.resultData,
12545 r.resultExtras, r.resultAbort, true);
12546 if (doNext) {
12547 doTrim = true;
12548 r.queue.processNextBroadcast(false);
12549 }
12550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012551
Christopher Tatef46723b2012-01-26 14:19:24 -080012552 if (rl.app != null) {
12553 rl.app.receivers.remove(rl);
12554 }
12555 removeReceiverLocked(rl);
12556 if (rl.linkedToDeath) {
12557 rl.linkedToDeath = false;
12558 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012560 }
12561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562
Christopher Tatef46723b2012-01-26 14:19:24 -080012563 // If we actually concluded any broadcasts, we might now be able
12564 // to trim the recipients' apps from our working set
12565 if (doTrim) {
12566 trimApplications();
12567 return;
12568 }
12569
12570 } finally {
12571 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573 }
12574
12575 void removeReceiverLocked(ReceiverList rl) {
12576 mRegisteredReceivers.remove(rl.receiver.asBinder());
12577 int N = rl.size();
12578 for (int i=0; i<N; i++) {
12579 mReceiverResolver.removeFilter(rl.get(i));
12580 }
12581 }
12582
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012583 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12584 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12585 ProcessRecord r = mLruProcesses.get(i);
12586 if (r.thread != null) {
12587 try {
12588 r.thread.dispatchPackageBroadcast(cmd, packages);
12589 } catch (RemoteException ex) {
12590 }
12591 }
12592 }
12593 }
12594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012595 private final int broadcastIntentLocked(ProcessRecord callerApp,
12596 String callerPackage, Intent intent, String resolvedType,
12597 IIntentReceiver resultTo, int resultCode, String resultData,
12598 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012599 boolean ordered, boolean sticky, int callingPid, int callingUid,
12600 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 intent = new Intent(intent);
12602
Dianne Hackborne7f97212011-02-24 14:40:20 -080012603 // By default broadcasts do not go to stopped apps.
12604 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12605
Joe Onorato8a9b2202010-02-26 18:56:32 -080012606 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012607 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012608 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012610 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012611 }
12612
12613 // Handle special intents: if this broadcast is from the package
12614 // manager about a package being removed, we need to remove all of
12615 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012616 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012617 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012618 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12619 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012620 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 || uidRemoved) {
12622 if (checkComponentPermission(
12623 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012624 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012625 == PackageManager.PERMISSION_GRANTED) {
12626 if (uidRemoved) {
12627 final Bundle intentExtras = intent.getExtras();
12628 final int uid = intentExtras != null
12629 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12630 if (uid >= 0) {
12631 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12632 synchronized (bs) {
12633 bs.removeUidStatsLocked(uid);
12634 }
12635 }
12636 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012637 // If resources are unvailble just force stop all
12638 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012639 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012640 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12641 if (list != null && (list.length > 0)) {
12642 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012643 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012644 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012645 sendPackageBroadcastLocked(
12646 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012647 }
12648 } else {
12649 Uri data = intent.getData();
12650 String ssp;
12651 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12652 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12653 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012654 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12655 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012656 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012657 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012658 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12659 new String[] {ssp});
12660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012661 }
12662 }
12663 }
12664 } else {
12665 String msg = "Permission Denial: " + intent.getAction()
12666 + " broadcast from " + callerPackage + " (pid=" + callingPid
12667 + ", uid=" + callingUid + ")"
12668 + " requires "
12669 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012670 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012671 throw new SecurityException(msg);
12672 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012673
12674 // Special case for adding a package: by default turn on compatibility
12675 // mode.
12676 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012677 Uri data = intent.getData();
12678 String ssp;
12679 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12680 mCompatModePackages.handlePackageAddedLocked(ssp,
12681 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 }
12684
12685 /*
12686 * If this is the time zone changed action, queue up a message that will reset the timezone
12687 * of all currently running processes. This message will get queued up before the broadcast
12688 * happens.
12689 */
12690 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12691 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12692 }
12693
Robert Greenwalt03595d02010-11-02 14:08:23 -070012694 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12695 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12696 }
12697
Robert Greenwalt434203a2010-10-11 16:00:27 -070012698 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12699 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12700 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12701 }
12702
Dianne Hackborn854060af2009-07-09 18:14:31 -070012703 /*
12704 * Prevent non-system code (defined here to be non-persistent
12705 * processes) from sending protected broadcasts.
12706 */
12707 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12708 || callingUid == Process.SHELL_UID || callingUid == 0) {
12709 // Always okay.
12710 } else if (callerApp == null || !callerApp.persistent) {
12711 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012712 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012713 intent.getAction())) {
12714 String msg = "Permission Denial: not allowed to send broadcast "
12715 + intent.getAction() + " from pid="
12716 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012717 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012718 throw new SecurityException(msg);
12719 }
12720 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012721 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012722 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012723 }
12724 }
12725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012726 // Add to the sticky list if requested.
12727 if (sticky) {
12728 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12729 callingPid, callingUid)
12730 != PackageManager.PERMISSION_GRANTED) {
12731 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12732 + callingPid + ", uid=" + callingUid
12733 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012734 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 throw new SecurityException(msg);
12736 }
12737 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012738 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012739 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012740 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012741 }
12742 if (intent.getComponent() != null) {
12743 throw new SecurityException(
12744 "Sticky broadcasts can't target a specific component");
12745 }
12746 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12747 if (list == null) {
12748 list = new ArrayList<Intent>();
12749 mStickyBroadcasts.put(intent.getAction(), list);
12750 }
12751 int N = list.size();
12752 int i;
12753 for (i=0; i<N; i++) {
12754 if (intent.filterEquals(list.get(i))) {
12755 // This sticky already exists, replace it.
12756 list.set(i, new Intent(intent));
12757 break;
12758 }
12759 }
12760 if (i >= N) {
12761 list.add(new Intent(intent));
12762 }
12763 }
12764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012765 // Figure out who all will receive this broadcast.
12766 List receivers = null;
12767 List<BroadcastFilter> registeredReceivers = null;
12768 try {
12769 if (intent.getComponent() != null) {
12770 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012771 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012772 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773 if (ai != null) {
12774 receivers = new ArrayList();
12775 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012776 if (isSingleton(ai.processName, ai.applicationInfo)) {
12777 ri.activityInfo = getActivityInfoForUser(ai, 0);
12778 } else {
12779 ri.activityInfo = getActivityInfoForUser(ai, userId);
12780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012781 receivers.add(ri);
12782 }
12783 } else {
12784 // Need to resolve the intent to interested receivers...
12785 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12786 == 0) {
12787 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012788 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012789 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012790 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012791 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12792 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 }
12794 } catch (RemoteException ex) {
12795 // pm is in same process, this will never happen.
12796 }
12797
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012798 final boolean replacePending =
12799 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12800
Joe Onorato8a9b2202010-02-26 18:56:32 -080012801 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012802 + " replacePending=" + replacePending);
12803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012804 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12805 if (!ordered && NR > 0) {
12806 // If we are not serializing this broadcast, then send the
12807 // registered receivers separately so they don't wait for the
12808 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012809 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12810 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012811 callerPackage, callingPid, callingUid, requiredPermission,
12812 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012813 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012814 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012815 TAG, "Enqueueing parallel broadcast " + r);
12816 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012817 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012818 queue.enqueueParallelBroadcastLocked(r);
12819 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 registeredReceivers = null;
12822 NR = 0;
12823 }
12824
12825 // Merge into one list.
12826 int ir = 0;
12827 if (receivers != null) {
12828 // A special case for PACKAGE_ADDED: do not allow the package
12829 // being added to see this broadcast. This prevents them from
12830 // using this as a back door to get run as soon as they are
12831 // installed. Maybe in the future we want to have a special install
12832 // broadcast or such for apps, but we'd like to deliberately make
12833 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012834 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012835 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12836 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12837 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012838 Uri data = intent.getData();
12839 if (data != null) {
12840 String pkgName = data.getSchemeSpecificPart();
12841 if (pkgName != null) {
12842 skipPackages = new String[] { pkgName };
12843 }
12844 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012845 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012846 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012847 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012848 if (skipPackages != null && (skipPackages.length > 0)) {
12849 for (String skipPackage : skipPackages) {
12850 if (skipPackage != null) {
12851 int NT = receivers.size();
12852 for (int it=0; it<NT; it++) {
12853 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12854 if (curt.activityInfo.packageName.equals(skipPackage)) {
12855 receivers.remove(it);
12856 it--;
12857 NT--;
12858 }
12859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012860 }
12861 }
12862 }
12863
12864 int NT = receivers != null ? receivers.size() : 0;
12865 int it = 0;
12866 ResolveInfo curt = null;
12867 BroadcastFilter curr = null;
12868 while (it < NT && ir < NR) {
12869 if (curt == null) {
12870 curt = (ResolveInfo)receivers.get(it);
12871 }
12872 if (curr == null) {
12873 curr = registeredReceivers.get(ir);
12874 }
12875 if (curr.getPriority() >= curt.priority) {
12876 // Insert this broadcast record into the final list.
12877 receivers.add(it, curr);
12878 ir++;
12879 curr = null;
12880 it++;
12881 NT++;
12882 } else {
12883 // Skip to the next ResolveInfo in the final list.
12884 it++;
12885 curt = null;
12886 }
12887 }
12888 }
12889 while (ir < NR) {
12890 if (receivers == null) {
12891 receivers = new ArrayList();
12892 }
12893 receivers.add(registeredReceivers.get(ir));
12894 ir++;
12895 }
12896
12897 if ((receivers != null && receivers.size() > 0)
12898 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012899 BroadcastQueue queue = broadcastQueueForIntent(intent);
12900 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012902 receivers, resultTo, resultCode, resultData, map, ordered,
12903 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012904 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012905 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012906 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012907 if (DEBUG_BROADCAST) {
12908 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012909 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012910 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012911 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012912 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012913 queue.enqueueOrderedBroadcastLocked(r);
12914 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 }
12917
Dianne Hackborna4972e92012-03-14 10:38:05 -070012918 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012919 }
12920
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012921 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012922 // Refuse possible leaked file descriptors
12923 if (intent != null && intent.hasFileDescriptors() == true) {
12924 throw new IllegalArgumentException("File descriptors passed in Intent");
12925 }
12926
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012927 int flags = intent.getFlags();
12928
12929 if (!mProcessesReady) {
12930 // if the caller really truly claims to know what they're doing, go
12931 // ahead and allow the broadcast without launching any receivers
12932 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12933 intent = new Intent(intent);
12934 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12935 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12936 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12937 + " before boot completion");
12938 throw new IllegalStateException("Cannot broadcast before boot completed");
12939 }
12940 }
12941
12942 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12943 throw new IllegalArgumentException(
12944 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12945 }
12946
12947 return intent;
12948 }
12949
12950 public final int broadcastIntent(IApplicationThread caller,
12951 Intent intent, String resolvedType, IIntentReceiver resultTo,
12952 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012953 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012954 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012955 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012956 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012958 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12959 final int callingPid = Binder.getCallingPid();
12960 final int callingUid = Binder.getCallingUid();
12961 final long origId = Binder.clearCallingIdentity();
12962 int res = broadcastIntentLocked(callerApp,
12963 callerApp != null ? callerApp.info.packageName : null,
12964 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012965 resultCode, resultData, map, requiredPermission, serialized, sticky,
12966 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 Binder.restoreCallingIdentity(origId);
12968 return res;
12969 }
12970 }
12971
12972 int broadcastIntentInPackage(String packageName, int uid,
12973 Intent intent, String resolvedType, IIntentReceiver resultTo,
12974 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012975 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012976 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012977 intent = verifyBroadcastLocked(intent);
12978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012979 final long origId = Binder.clearCallingIdentity();
12980 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12981 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012982 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012983 Binder.restoreCallingIdentity(origId);
12984 return res;
12985 }
12986 }
12987
Amith Yamasani742a6712011-05-04 14:49:28 -070012988 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12989 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012990 // Refuse possible leaked file descriptors
12991 if (intent != null && intent.hasFileDescriptors() == true) {
12992 throw new IllegalArgumentException("File descriptors passed in Intent");
12993 }
12994
12995 synchronized(this) {
12996 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12997 != PackageManager.PERMISSION_GRANTED) {
12998 String msg = "Permission Denial: unbroadcastIntent() from pid="
12999 + Binder.getCallingPid()
13000 + ", uid=" + Binder.getCallingUid()
13001 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013002 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013003 throw new SecurityException(msg);
13004 }
13005 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13006 if (list != null) {
13007 int N = list.size();
13008 int i;
13009 for (i=0; i<N; i++) {
13010 if (intent.filterEquals(list.get(i))) {
13011 list.remove(i);
13012 break;
13013 }
13014 }
13015 }
13016 }
13017 }
13018
13019 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13020 String resultData, Bundle resultExtras, boolean resultAbort,
13021 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013022 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13023 if (r == null) {
13024 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 return false;
13026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013027
Christopher Tatef46723b2012-01-26 14:19:24 -080013028 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13029 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013030 }
13031
13032 public void finishReceiver(IBinder who, int resultCode, String resultData,
13033 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013034 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013035
13036 // Refuse possible leaked file descriptors
13037 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13038 throw new IllegalArgumentException("File descriptors passed in Bundle");
13039 }
13040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013041 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013042 try {
13043 boolean doNext = false;
13044 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045
Christopher Tatef46723b2012-01-26 14:19:24 -080013046 synchronized(this) {
13047 r = broadcastRecordForReceiverLocked(who);
13048 if (r != null) {
13049 doNext = r.queue.finishReceiverLocked(r, resultCode,
13050 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013052 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013053
Christopher Tatef46723b2012-01-26 14:19:24 -080013054 if (doNext) {
13055 r.queue.processNextBroadcast(false);
13056 }
13057 trimApplications();
13058 } finally {
13059 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 // =========================================================
13064 // INSTRUMENTATION
13065 // =========================================================
13066
13067 public boolean startInstrumentation(ComponentName className,
13068 String profileFile, int flags, Bundle arguments,
13069 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013070 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013071 // Refuse possible leaked file descriptors
13072 if (arguments != null && arguments.hasFileDescriptors()) {
13073 throw new IllegalArgumentException("File descriptors passed in Bundle");
13074 }
13075
13076 synchronized(this) {
13077 InstrumentationInfo ii = null;
13078 ApplicationInfo ai = null;
13079 try {
13080 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013081 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013083 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013084 } catch (PackageManager.NameNotFoundException e) {
13085 }
13086 if (ii == null) {
13087 reportStartInstrumentationFailure(watcher, className,
13088 "Unable to find instrumentation info for: " + className);
13089 return false;
13090 }
13091 if (ai == null) {
13092 reportStartInstrumentationFailure(watcher, className,
13093 "Unable to find instrumentation target package: " + ii.targetPackage);
13094 return false;
13095 }
13096
13097 int match = mContext.getPackageManager().checkSignatures(
13098 ii.targetPackage, ii.packageName);
13099 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13100 String msg = "Permission Denial: starting instrumentation "
13101 + className + " from pid="
13102 + Binder.getCallingPid()
13103 + ", uid=" + Binder.getCallingPid()
13104 + " not allowed because package " + ii.packageName
13105 + " does not have a signature matching the target "
13106 + ii.targetPackage;
13107 reportStartInstrumentationFailure(watcher, className, msg);
13108 throw new SecurityException(msg);
13109 }
13110
Amith Yamasani483f3b02012-03-13 16:08:00 -070013111 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013112 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013113 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013114 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013115 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013117 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 app.instrumentationProfileFile = profileFile;
13119 app.instrumentationArguments = arguments;
13120 app.instrumentationWatcher = watcher;
13121 app.instrumentationResultClass = className;
13122 Binder.restoreCallingIdentity(origId);
13123 }
13124
13125 return true;
13126 }
13127
13128 /**
13129 * Report errors that occur while attempting to start Instrumentation. Always writes the
13130 * error to the logs, but if somebody is watching, send the report there too. This enables
13131 * the "am" command to report errors with more information.
13132 *
13133 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13134 * @param cn The component name of the instrumentation.
13135 * @param report The error report.
13136 */
13137 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13138 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013139 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013140 try {
13141 if (watcher != null) {
13142 Bundle results = new Bundle();
13143 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13144 results.putString("Error", report);
13145 watcher.instrumentationStatus(cn, -1, results);
13146 }
13147 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013148 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013149 }
13150 }
13151
13152 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13153 if (app.instrumentationWatcher != null) {
13154 try {
13155 // NOTE: IInstrumentationWatcher *must* be oneway here
13156 app.instrumentationWatcher.instrumentationFinished(
13157 app.instrumentationClass,
13158 resultCode,
13159 results);
13160 } catch (RemoteException e) {
13161 }
13162 }
13163 app.instrumentationWatcher = null;
13164 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013165 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013166 app.instrumentationProfileFile = null;
13167 app.instrumentationArguments = null;
13168
Amith Yamasani483f3b02012-03-13 16:08:00 -070013169 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013170 }
13171
13172 public void finishInstrumentation(IApplicationThread target,
13173 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013174 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 // Refuse possible leaked file descriptors
13176 if (results != null && results.hasFileDescriptors()) {
13177 throw new IllegalArgumentException("File descriptors passed in Intent");
13178 }
13179
13180 synchronized(this) {
13181 ProcessRecord app = getRecordForAppLocked(target);
13182 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013183 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013184 return;
13185 }
13186 final long origId = Binder.clearCallingIdentity();
13187 finishInstrumentationLocked(app, resultCode, results);
13188 Binder.restoreCallingIdentity(origId);
13189 }
13190 }
13191
13192 // =========================================================
13193 // CONFIGURATION
13194 // =========================================================
13195
13196 public ConfigurationInfo getDeviceConfigurationInfo() {
13197 ConfigurationInfo config = new ConfigurationInfo();
13198 synchronized (this) {
13199 config.reqTouchScreen = mConfiguration.touchscreen;
13200 config.reqKeyboardType = mConfiguration.keyboard;
13201 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013202 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13203 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013204 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13205 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013206 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13207 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013208 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13209 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013210 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211 }
13212 return config;
13213 }
13214
13215 public Configuration getConfiguration() {
13216 Configuration ci;
13217 synchronized(this) {
13218 ci = new Configuration(mConfiguration);
13219 }
13220 return ci;
13221 }
13222
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013223 public void updatePersistentConfiguration(Configuration values) {
13224 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13225 "updateConfiguration()");
13226 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13227 "updateConfiguration()");
13228 if (values == null) {
13229 throw new NullPointerException("Configuration must not be null");
13230 }
13231
13232 synchronized(this) {
13233 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013234 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013235 Binder.restoreCallingIdentity(origId);
13236 }
13237 }
13238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013239 public void updateConfiguration(Configuration values) {
13240 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13241 "updateConfiguration()");
13242
13243 synchronized(this) {
13244 if (values == null && mWindowManager != null) {
13245 // sentinel: fetch the current configuration from the window manager
13246 values = mWindowManager.computeNewConfiguration();
13247 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013248
13249 if (mWindowManager != null) {
13250 mProcessList.applyDisplaySize(mWindowManager);
13251 }
13252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013254 if (values != null) {
13255 Settings.System.clearConfiguration(values);
13256 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013257 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013258 Binder.restoreCallingIdentity(origId);
13259 }
13260 }
13261
13262 /**
13263 * Do either or both things: (1) change the current configuration, and (2)
13264 * make sure the given activity is running with the (now) current
13265 * configuration. Returns true if the activity has been left running, or
13266 * false if <var>starting</var> is being destroyed to match the new
13267 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013268 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013269 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013270 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013271 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013272 // do nothing if we are headless
13273 if (mHeadless) return true;
13274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013275 int changes = 0;
13276
13277 boolean kept = true;
13278
13279 if (values != null) {
13280 Configuration newConfig = new Configuration(mConfiguration);
13281 changes = newConfig.updateFrom(values);
13282 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013283 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013284 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013285 }
13286
Doug Zongker2bec3d42009-12-04 12:52:44 -080013287 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013288
Dianne Hackborn813075a62011-11-14 17:45:19 -080013289 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013290 saveLocaleLocked(values.locale,
13291 !values.locale.equals(mConfiguration.locale),
13292 values.userSetLocale);
13293 }
13294
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013295 mConfigurationSeq++;
13296 if (mConfigurationSeq <= 0) {
13297 mConfigurationSeq = 1;
13298 }
13299 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013300 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013301 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013302
13303 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013304
13305 // TODO: If our config changes, should we auto dismiss any currently
13306 // showing dialogs?
13307 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013308
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013309 AttributeCache ac = AttributeCache.instance();
13310 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013311 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013313
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013314 // Make sure all resources in our process are updated
13315 // right now, so that anyone who is going to retrieve
13316 // resource values after we return will be sure to get
13317 // the new ones. This is especially important during
13318 // boot, where the first config change needs to guarantee
13319 // all resources have that config before following boot
13320 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013321 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013322
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013323 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013324 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013325 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013326 mHandler.sendMessage(msg);
13327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013328
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013329 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13330 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331 try {
13332 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013333 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013334 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013335 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013336 }
13337 } catch (Exception e) {
13338 }
13339 }
13340 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013341 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13342 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013343 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013344 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013345 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13346 broadcastIntentLocked(null, null,
13347 new Intent(Intent.ACTION_LOCALE_CHANGED),
13348 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013349 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013351 }
13352 }
13353
13354 if (changes != 0 && starting == null) {
13355 // If the configuration changed, and the caller is not already
13356 // in the process of starting an activity, then find the top
13357 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013358 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013359 }
13360
13361 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013362 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013363 // And we need to make sure at this point that all other activities
13364 // are made visible with the correct configuration.
13365 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013366 }
13367
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013368 if (values != null && mWindowManager != null) {
13369 mWindowManager.setNewConfiguration(mConfiguration);
13370 }
13371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013372 return kept;
13373 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013374
13375 /**
13376 * Decide based on the configuration whether we should shouw the ANR,
13377 * crash, etc dialogs. The idea is that if there is no affordnace to
13378 * press the on-screen buttons, we shouldn't show the dialog.
13379 *
13380 * A thought: SystemUI might also want to get told about this, the Power
13381 * dialog / global actions also might want different behaviors.
13382 */
13383 private static final boolean shouldShowDialogs(Configuration config) {
13384 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13385 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013387
13388 /**
13389 * Save the locale. You must be inside a synchronized (this) block.
13390 */
13391 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13392 if(isDiff) {
13393 SystemProperties.set("user.language", l.getLanguage());
13394 SystemProperties.set("user.region", l.getCountry());
13395 }
13396
13397 if(isPersist) {
13398 SystemProperties.set("persist.sys.language", l.getLanguage());
13399 SystemProperties.set("persist.sys.country", l.getCountry());
13400 SystemProperties.set("persist.sys.localevar", l.getVariant());
13401 }
13402 }
13403
Adam Powelldd8fab22012-03-22 17:47:27 -070013404 @Override
13405 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13406 ActivityRecord srec = ActivityRecord.forToken(token);
13407 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13408 }
13409
13410 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13411 Intent resultData) {
13412 ComponentName dest = destIntent.getComponent();
13413
13414 synchronized (this) {
13415 ActivityRecord srec = ActivityRecord.forToken(token);
13416 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13417 final int start = history.indexOf(srec);
13418 if (start < 0) {
13419 // Current activity is not in history stack; do nothing.
13420 return false;
13421 }
13422 int finishTo = start - 1;
13423 ActivityRecord parent = null;
13424 boolean foundParentInTask = false;
13425 if (dest != null) {
13426 TaskRecord tr = srec.task;
13427 for (int i = start - 1; i >= 0; i--) {
13428 ActivityRecord r = history.get(i);
13429 if (tr != r.task) {
13430 // Couldn't find parent in the same task; stop at the one above this.
13431 // (Root of current task; in-app "home" behavior)
13432 // Always at least finish the current activity.
13433 finishTo = Math.min(start - 1, i + 1);
13434 parent = history.get(finishTo);
13435 break;
13436 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13437 r.info.name.equals(dest.getClassName())) {
13438 finishTo = i;
13439 parent = r;
13440 foundParentInTask = true;
13441 break;
13442 }
13443 }
13444 }
13445
13446 if (mController != null) {
13447 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13448 if (next != null) {
13449 // ask watcher if this is allowed
13450 boolean resumeOK = true;
13451 try {
13452 resumeOK = mController.activityResuming(next.packageName);
13453 } catch (RemoteException e) {
13454 mController = null;
13455 }
13456
13457 if (!resumeOK) {
13458 return false;
13459 }
13460 }
13461 }
13462 final long origId = Binder.clearCallingIdentity();
13463 for (int i = start; i > finishTo; i--) {
13464 ActivityRecord r = history.get(i);
13465 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13466 "navigate-up");
13467 // Only return the supplied result for the first activity finished
13468 resultCode = Activity.RESULT_CANCELED;
13469 resultData = null;
13470 }
13471
13472 if (parent != null && foundParentInTask) {
13473 final int parentLaunchMode = parent.info.launchMode;
13474 final int destIntentFlags = destIntent.getFlags();
13475 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13476 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13477 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13478 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13479 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13480 } else {
13481 try {
13482 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13483 destIntent.getComponent(), 0, UserId.getCallingUserId());
13484 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13485 null, aInfo, parent.appToken, null,
13486 0, -1, parent.launchedFromUid, 0, null, true, null);
13487 foundParentInTask = res == ActivityManager.START_SUCCESS;
13488 } catch (RemoteException e) {
13489 foundParentInTask = false;
13490 }
13491 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13492 resultData, "navigate-up");
13493 }
13494 }
13495 Binder.restoreCallingIdentity(origId);
13496 return foundParentInTask;
13497 }
13498 }
13499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013500 // =========================================================
13501 // LIFETIME MANAGEMENT
13502 // =========================================================
13503
Christopher Tatef46723b2012-01-26 14:19:24 -080013504 // Returns which broadcast queue the app is the current [or imminent] receiver
13505 // on, or 'null' if the app is not an active broadcast recipient.
13506 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13507 BroadcastRecord r = app.curReceiver;
13508 if (r != null) {
13509 return r.queue;
13510 }
13511
13512 // It's not the current receiver, but it might be starting up to become one
13513 synchronized (this) {
13514 for (BroadcastQueue queue : mBroadcastQueues) {
13515 r = queue.mPendingBroadcast;
13516 if (r != null && r.curApp == app) {
13517 // found it; report which queue it's in
13518 return queue;
13519 }
13520 }
13521 }
13522
13523 return null;
13524 }
13525
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013526 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013527 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013528 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013529 // This adjustment has already been computed. If we are calling
13530 // from the top, we may have already computed our adjustment with
13531 // an earlier hidden adjustment that isn't really for us... if
13532 // so, use the new hidden adjustment.
13533 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013534 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013535 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013536 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 }
13538
13539 if (app.thread == null) {
13540 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013541 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013542 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013543 }
13544
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013545 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13546 app.adjSource = null;
13547 app.adjTarget = null;
13548 app.empty = false;
13549 app.hidden = false;
13550
13551 final int activitiesSize = app.activities.size();
13552
Dianne Hackborn7d608422011-08-07 16:24:18 -070013553 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013554 // The max adjustment doesn't allow this app to be anything
13555 // below foreground, so it is not worth doing work for it.
13556 app.adjType = "fixed";
13557 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013558 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013559 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013560 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013561 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013562 // System process can do UI, and when they do we want to have
13563 // them trim their memory after the user leaves the UI. To
13564 // facilitate this, here we need to determine whether or not it
13565 // is currently showing UI.
13566 app.systemNoUi = true;
13567 if (app == TOP_APP) {
13568 app.systemNoUi = false;
13569 } else if (activitiesSize > 0) {
13570 for (int j = 0; j < activitiesSize; j++) {
13571 final ActivityRecord r = app.activities.get(j);
13572 if (r.visible) {
13573 app.systemNoUi = false;
13574 break;
13575 }
13576 }
13577 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013578 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013579 }
13580
13581 final boolean hadForegroundActivities = app.foregroundActivities;
13582
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013583 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013584 app.keeping = false;
13585 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013586
The Android Open Source Project4df24232009-03-05 14:34:35 -080013587 // Determine the importance of the process, starting with most
13588 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013589 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013590 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013591 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013592 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013593 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013594 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013595 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013596 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013597 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013598 } else if (app.instrumentationClass != null) {
13599 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013600 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013601 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013602 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013603 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013605 // counts as being in the foreground for OOM killer purposes.
13606 // It's placed in a sched group based on the nature of the
13607 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013608 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013609 schedGroup = (queue == mFgBroadcastQueue)
13610 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013611 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612 } else if (app.executingServices.size() > 0) {
13613 // An app that is currently executing a service callback also
13614 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013615 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013616 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013617 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013618 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013619 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013620 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013621 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013622 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013623 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013624 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013625 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013626 // A very not-needed process. If this is lower in the lru list,
13627 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013628 adj = hiddenAdj;
13629 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013630 app.hidden = true;
13631 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013632 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013633 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013634
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013635 boolean hasStoppingActivities = false;
13636
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013637 // Examine all activities if not already foreground.
13638 if (!app.foregroundActivities && activitiesSize > 0) {
13639 for (int j = 0; j < activitiesSize; j++) {
13640 final ActivityRecord r = app.activities.get(j);
13641 if (r.visible) {
13642 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013643 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13644 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013645 app.adjType = "visible";
13646 }
13647 schedGroup = Process.THREAD_GROUP_DEFAULT;
13648 app.hidden = false;
13649 app.foregroundActivities = true;
13650 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013651 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013652 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13653 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013654 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013655 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013656 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013657 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013658 } else if (r.state == ActivityState.STOPPING) {
13659 // We will apply the actual adjustment later, because
13660 // we want to allow this process to immediately go through
13661 // any memory trimming that is in effect.
13662 app.hidden = false;
13663 app.foregroundActivities = true;
13664 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013665 }
13666 }
13667 }
13668
Dianne Hackborn7d608422011-08-07 16:24:18 -070013669 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013670 if (app.foregroundServices) {
13671 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013672 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013673 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013674 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013675 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013676 } else if (app.forcingToForeground != null) {
13677 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013678 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013679 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013680 app.adjType = "force-foreground";
13681 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013682 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013683 }
13684 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013685
Dianne Hackborn7d608422011-08-07 16:24:18 -070013686 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013687 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013688 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013689 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013690 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013691 app.adjType = "heavy";
13692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013693
Dianne Hackborn7d608422011-08-07 16:24:18 -070013694 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013695 // This process is hosting what we currently consider to be the
13696 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013697 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013698 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013699 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013700 app.adjType = "home";
13701 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013702
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013703 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13704 && app.activities.size() > 0) {
13705 // This was the previous process that showed UI to the user.
13706 // We want to try to keep it around more aggressively, to give
13707 // a good experience around switching between two apps.
13708 adj = ProcessList.PREVIOUS_APP_ADJ;
13709 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13710 app.hidden = false;
13711 app.adjType = "previous";
13712 }
13713
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013714 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13715 + " reason=" + app.adjType);
13716
The Android Open Source Project4df24232009-03-05 14:34:35 -080013717 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013718 // there are applications dependent on our services or providers, but
13719 // this gives us a baseline and makes sure we don't get into an
13720 // infinite recursion.
13721 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013722 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013723
Christopher Tate6fa95972009-06-05 18:43:55 -070013724 if (mBackupTarget != null && app == mBackupTarget.app) {
13725 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013726 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013727 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013728 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013729 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013730 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013731 }
13732 }
13733
Dianne Hackborn7d608422011-08-07 16:24:18 -070013734 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013735 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013736 final long now = SystemClock.uptimeMillis();
13737 // This process is more important if the top activity is
13738 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013739 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013740 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013741 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013742 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013743 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013744 // If this process has shown some UI, let it immediately
13745 // go to the LRU list because it may be pretty heavy with
13746 // UI stuff. We'll tag it with a label just to help
13747 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013748 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013749 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013750 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013751 } else {
13752 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13753 // This service has seen some activity within
13754 // recent memory, so we will keep its process ahead
13755 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013756 if (adj > ProcessList.SERVICE_ADJ) {
13757 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013758 app.adjType = "started-services";
13759 app.hidden = false;
13760 }
13761 }
13762 // If we have let the service slide into the background
13763 // state, still have some text describing what it is doing
13764 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013765 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013766 app.adjType = "started-bg-services";
13767 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013768 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013769 // Don't kill this process because it is doing work; it
13770 // has said it is doing work.
13771 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013772 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013773 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013774 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013775 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013776 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013777 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013778 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013779 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013780 // XXX should compute this based on the max of
13781 // all connected clients.
13782 ConnectionRecord cr = clist.get(i);
13783 if (cr.binding.client == app) {
13784 // Binding to ourself is not interesting.
13785 continue;
13786 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013787 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013788 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013789 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013790 int myHiddenAdj = hiddenAdj;
13791 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013792 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013793 myHiddenAdj = client.hiddenAdj;
13794 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013795 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013796 }
13797 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013798 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013799 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013800 String adjType = null;
13801 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13802 // Not doing bind OOM management, so treat
13803 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013804 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013805 // If this process has shown some UI, let it immediately
13806 // go to the LRU list because it may be pretty heavy with
13807 // UI stuff. We'll tag it with a label just to help
13808 // debug and understand what is going on.
13809 if (adj > clientAdj) {
13810 adjType = "bound-bg-ui-services";
13811 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013812 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013813 clientAdj = adj;
13814 } else {
13815 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13816 // This service has not seen activity within
13817 // recent memory, so allow it to drop to the
13818 // LRU list if there is no other reason to keep
13819 // it around. We'll also tag it with a label just
13820 // to help debug and undertand what is going on.
13821 if (adj > clientAdj) {
13822 adjType = "bound-bg-services";
13823 }
13824 clientAdj = adj;
13825 }
13826 }
13827 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013828 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013829 // If this process has recently shown UI, and
13830 // the process that is binding to it is less
13831 // important than being visible, then we don't
13832 // care about the binding as much as we care
13833 // about letting this process get into the LRU
13834 // list to be killed and restarted if needed for
13835 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013836 if (app.hasShownUi && app != mHomeProcess
13837 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013838 adjType = "bound-bg-ui-services";
13839 } else {
13840 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13841 |Context.BIND_IMPORTANT)) != 0) {
13842 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013843 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13844 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13845 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13846 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13847 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013848 adj = clientAdj;
13849 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013850 app.pendingUiClean = true;
13851 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13852 adj = ProcessList.VISIBLE_APP_ADJ;
13853 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013854 }
13855 if (!client.hidden) {
13856 app.hidden = false;
13857 }
13858 if (client.keeping) {
13859 app.keeping = true;
13860 }
13861 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013862 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013863 }
13864 if (adjType != null) {
13865 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013866 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13867 .REASON_SERVICE_IN_USE;
13868 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013869 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013870 app.adjTarget = s.name;
13871 }
13872 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13873 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13874 schedGroup = Process.THREAD_GROUP_DEFAULT;
13875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013876 }
13877 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013878 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13879 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013880 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013881 (a.visible || a.state == ActivityState.RESUMED
13882 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013883 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013884 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13885 schedGroup = Process.THREAD_GROUP_DEFAULT;
13886 }
13887 app.hidden = false;
13888 app.adjType = "service";
13889 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13890 .REASON_SERVICE_IN_USE;
13891 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013892 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013893 app.adjTarget = s.name;
13894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013896 }
13897 }
13898 }
13899 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013900
Dianne Hackborn287952c2010-09-22 22:34:31 -070013901 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013902 // would like to avoid killing it unless it would prevent the current
13903 // application from running. By default we put the process in
13904 // with the rest of the background processes; as we scan through
13905 // its services we may bump it up from there.
13906 if (adj > hiddenAdj) {
13907 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013908 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013909 app.adjType = "bg-services";
13910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 }
13912
Dianne Hackborn7d608422011-08-07 16:24:18 -070013913 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013914 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013915 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013916 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013917 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013918 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013919 if (cpr.clients.size() != 0) {
13920 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013921 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013922 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013923 if (client == app) {
13924 // Being our own client is not interesting.
13925 continue;
13926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013927 int myHiddenAdj = hiddenAdj;
13928 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013929 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013930 myHiddenAdj = client.hiddenAdj;
13931 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013932 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013933 }
13934 }
13935 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013936 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013938 if (app.hasShownUi && app != mHomeProcess
13939 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013940 app.adjType = "bg-ui-provider";
13941 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013942 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13943 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013944 app.adjType = "provider";
13945 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013946 if (!client.hidden) {
13947 app.hidden = false;
13948 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013949 if (client.keeping) {
13950 app.keeping = true;
13951 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013952 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13953 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013954 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013955 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013956 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013957 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013958 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13959 schedGroup = Process.THREAD_GROUP_DEFAULT;
13960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013961 }
13962 }
13963 // If the provider has external (non-framework) process
13964 // dependencies, ensure that its adjustment is at least
13965 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013966 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013967 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13968 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013969 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013970 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013971 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013972 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013973 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013974 }
13975 }
13976 }
13977 }
13978
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013979 if (adj == ProcessList.SERVICE_ADJ) {
13980 if (doingAll) {
13981 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13982 mNewNumServiceProcs++;
13983 }
13984 if (app.serviceb) {
13985 adj = ProcessList.SERVICE_B_ADJ;
13986 }
13987 } else {
13988 app.serviceb = false;
13989 }
13990
13991 app.nonStoppingAdj = adj;
13992
13993 if (hasStoppingActivities) {
13994 // Only upgrade adjustment.
13995 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13996 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13997 app.adjType = "stopping";
13998 }
13999 }
14000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014001 app.curRawAdj = adj;
14002
Joe Onorato8a9b2202010-02-26 18:56:32 -080014003 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014004 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14005 if (adj > app.maxAdj) {
14006 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014007 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014008 schedGroup = Process.THREAD_GROUP_DEFAULT;
14009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014010 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014011 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014012 app.keeping = true;
14013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014014
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014015 if (app.hasAboveClient) {
14016 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14017 // then we need to drop its adjustment to be lower than the service's
14018 // in order to honor the request. We want to drop it by one adjustment
14019 // level... but there is special meaning applied to various levels so
14020 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014021 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014022 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014023 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14024 adj = ProcessList.VISIBLE_APP_ADJ;
14025 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14026 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14027 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14028 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014029 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014030 adj++;
14031 }
14032 }
14033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014034 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014035 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014036
14037 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014038 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14039 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014040 }
14041
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014042 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014043 }
14044
14045 /**
14046 * Ask a given process to GC right now.
14047 */
14048 final void performAppGcLocked(ProcessRecord app) {
14049 try {
14050 app.lastRequestedGc = SystemClock.uptimeMillis();
14051 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014052 if (app.reportLowMemory) {
14053 app.reportLowMemory = false;
14054 app.thread.scheduleLowMemory();
14055 } else {
14056 app.thread.processInBackground();
14057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014058 }
14059 } catch (Exception e) {
14060 // whatever.
14061 }
14062 }
14063
14064 /**
14065 * Returns true if things are idle enough to perform GCs.
14066 */
Josh Bartel7f208742010-02-25 11:01:44 -060014067 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014068 boolean processingBroadcasts = false;
14069 for (BroadcastQueue q : mBroadcastQueues) {
14070 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14071 processingBroadcasts = true;
14072 }
14073 }
14074 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014075 && (mSleeping || (mMainStack.mResumedActivity != null &&
14076 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014077 }
14078
14079 /**
14080 * Perform GCs on all processes that are waiting for it, but only
14081 * if things are idle.
14082 */
14083 final void performAppGcsLocked() {
14084 final int N = mProcessesToGc.size();
14085 if (N <= 0) {
14086 return;
14087 }
Josh Bartel7f208742010-02-25 11:01:44 -060014088 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014089 while (mProcessesToGc.size() > 0) {
14090 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014091 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014092 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14093 <= SystemClock.uptimeMillis()) {
14094 // To avoid spamming the system, we will GC processes one
14095 // at a time, waiting a few seconds between each.
14096 performAppGcLocked(proc);
14097 scheduleAppGcsLocked();
14098 return;
14099 } else {
14100 // It hasn't been long enough since we last GCed this
14101 // process... put it in the list to wait for its time.
14102 addProcessToGcListLocked(proc);
14103 break;
14104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 }
14106 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014107
14108 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014109 }
14110 }
14111
14112 /**
14113 * If all looks good, perform GCs on all processes waiting for them.
14114 */
14115 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014116 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014117 performAppGcsLocked();
14118 return;
14119 }
14120 // Still not idle, wait some more.
14121 scheduleAppGcsLocked();
14122 }
14123
14124 /**
14125 * Schedule the execution of all pending app GCs.
14126 */
14127 final void scheduleAppGcsLocked() {
14128 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014129
14130 if (mProcessesToGc.size() > 0) {
14131 // Schedule a GC for the time to the next process.
14132 ProcessRecord proc = mProcessesToGc.get(0);
14133 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14134
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014135 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014136 long now = SystemClock.uptimeMillis();
14137 if (when < (now+GC_TIMEOUT)) {
14138 when = now + GC_TIMEOUT;
14139 }
14140 mHandler.sendMessageAtTime(msg, when);
14141 }
14142 }
14143
14144 /**
14145 * Add a process to the array of processes waiting to be GCed. Keeps the
14146 * list in sorted order by the last GC time. The process can't already be
14147 * on the list.
14148 */
14149 final void addProcessToGcListLocked(ProcessRecord proc) {
14150 boolean added = false;
14151 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14152 if (mProcessesToGc.get(i).lastRequestedGc <
14153 proc.lastRequestedGc) {
14154 added = true;
14155 mProcessesToGc.add(i+1, proc);
14156 break;
14157 }
14158 }
14159 if (!added) {
14160 mProcessesToGc.add(0, proc);
14161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014162 }
14163
14164 /**
14165 * Set up to ask a process to GC itself. This will either do it
14166 * immediately, or put it on the list of processes to gc the next
14167 * time things are idle.
14168 */
14169 final void scheduleAppGcLocked(ProcessRecord app) {
14170 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014171 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014172 return;
14173 }
14174 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014175 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014176 scheduleAppGcsLocked();
14177 }
14178 }
14179
Dianne Hackborn287952c2010-09-22 22:34:31 -070014180 final void checkExcessivePowerUsageLocked(boolean doKills) {
14181 updateCpuStatsNow();
14182
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014183 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014184 boolean doWakeKills = doKills;
14185 boolean doCpuKills = doKills;
14186 if (mLastPowerCheckRealtime == 0) {
14187 doWakeKills = false;
14188 }
14189 if (mLastPowerCheckUptime == 0) {
14190 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014191 }
14192 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014193 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014194 }
14195 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014196 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14197 final long curUptime = SystemClock.uptimeMillis();
14198 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14199 mLastPowerCheckRealtime = curRealtime;
14200 mLastPowerCheckUptime = curUptime;
14201 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14202 doWakeKills = false;
14203 }
14204 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14205 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014206 }
14207 int i = mLruProcesses.size();
14208 while (i > 0) {
14209 i--;
14210 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014211 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014212 long wtime;
14213 synchronized (stats) {
14214 wtime = stats.getProcessWakeTime(app.info.uid,
14215 app.pid, curRealtime);
14216 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014217 long wtimeUsed = wtime - app.lastWakeTime;
14218 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14219 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014220 StringBuilder sb = new StringBuilder(128);
14221 sb.append("Wake for ");
14222 app.toShortString(sb);
14223 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014224 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014225 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014226 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014227 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014228 sb.append((wtimeUsed*100)/realtimeSince);
14229 sb.append("%)");
14230 Slog.i(TAG, sb.toString());
14231 sb.setLength(0);
14232 sb.append("CPU for ");
14233 app.toShortString(sb);
14234 sb.append(": over ");
14235 TimeUtils.formatDuration(uptimeSince, sb);
14236 sb.append(" used ");
14237 TimeUtils.formatDuration(cputimeUsed, sb);
14238 sb.append(" (");
14239 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014240 sb.append("%)");
14241 Slog.i(TAG, sb.toString());
14242 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014243 // If a process has held a wake lock for more
14244 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014245 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014246 if (doWakeKills && realtimeSince > 0
14247 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14248 synchronized (stats) {
14249 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14250 realtimeSince, wtimeUsed);
14251 }
14252 Slog.w(TAG, "Excessive wake lock in " + app.processName
14253 + " (pid " + app.pid + "): held " + wtimeUsed
14254 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014255 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14256 app.processName, app.setAdj, "excessive wake lock");
14257 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014258 } else if (doCpuKills && uptimeSince > 0
14259 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14260 synchronized (stats) {
14261 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14262 uptimeSince, cputimeUsed);
14263 }
14264 Slog.w(TAG, "Excessive CPU in " + app.processName
14265 + " (pid " + app.pid + "): used " + cputimeUsed
14266 + " during " + uptimeSince);
14267 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14268 app.processName, app.setAdj, "excessive cpu");
14269 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014270 } else {
14271 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014272 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014273 }
14274 }
14275 }
14276 }
14277
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014278 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014279 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014280 app.hiddenAdj = hiddenAdj;
14281
14282 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014283 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014284 }
14285
Dianne Hackborn287952c2010-09-22 22:34:31 -070014286 final boolean wasKeeping = app.keeping;
14287
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014288 boolean success = true;
14289
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014290 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014291
Jeff Brown10e89712011-07-08 18:52:57 -070014292 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014293 if (wasKeeping && !app.keeping) {
14294 // This app is no longer something we want to keep. Note
14295 // its current wake lock time to later know to kill it if
14296 // it is not behaving well.
14297 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14298 synchronized (stats) {
14299 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14300 app.pid, SystemClock.elapsedRealtime());
14301 }
14302 app.lastCpuTime = app.curCpuTime;
14303 }
14304
14305 app.setRawAdj = app.curRawAdj;
14306 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014307
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014308 if (app.curAdj != app.setAdj) {
14309 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014310 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014311 TAG, "Set " + app.pid + " " + app.processName +
14312 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014313 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014314 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014315 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014316 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014317 }
14318 }
14319 if (app.setSchedGroup != app.curSchedGroup) {
14320 app.setSchedGroup = app.curSchedGroup;
14321 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14322 "Setting process group of " + app.processName
14323 + " to " + app.curSchedGroup);
14324 if (app.waitingToKill != null &&
14325 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14326 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14327 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14328 app.processName, app.setAdj, app.waitingToKill);
14329 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014330 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014331 } else {
14332 if (true) {
14333 long oldId = Binder.clearCallingIdentity();
14334 try {
14335 Process.setProcessGroup(app.pid, app.curSchedGroup);
14336 } catch (Exception e) {
14337 Slog.w(TAG, "Failed setting process group of " + app.pid
14338 + " to " + app.curSchedGroup);
14339 e.printStackTrace();
14340 } finally {
14341 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014342 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014343 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014344 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014345 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014346 app.thread.setSchedulingGroup(app.curSchedGroup);
14347 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014348 }
14349 }
14350 }
14351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014352 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014353 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014354 }
14355
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014356 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014357 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014358 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014359 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014360 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014361 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014362 }
14363 }
14364 return resumedActivity;
14365 }
14366
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014367 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014368 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014369 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14370 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014371 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14372 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014373
14374 mAdjSeq++;
14375
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014376 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014377 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14378 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014379 if (nowHidden != wasHidden) {
14380 // Changed to/from hidden state, so apps after it in the LRU
14381 // list may also be changed.
14382 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014383 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014384 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014385 }
14386
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014387 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014388 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14390
14391 if (false) {
14392 RuntimeException e = new RuntimeException();
14393 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014394 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014395 }
14396
14397 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014398 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014399
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014400 // Let's determine how many processes we have running vs.
14401 // how many slots we have for background processes; we may want
14402 // to put multiple processes in a slot of there are enough of
14403 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014404 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014405 int factor = (mLruProcesses.size()-4)/numSlots;
14406 if (factor < 1) factor = 1;
14407 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014408 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014409 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014410
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014411 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014412 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014413 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014414 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014415 while (i > 0) {
14416 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014417 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014418 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014419 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14420 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014421 && app.curAdj == curHiddenAdj) {
14422 step++;
14423 if (step >= factor) {
14424 step = 0;
14425 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014426 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014427 }
14428 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014429 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014430 numHidden++;
14431 if (numHidden > mProcessLimit) {
14432 Slog.i(TAG, "No longer want " + app.processName
14433 + " (pid " + app.pid + "): hidden #" + numHidden);
14434 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14435 app.processName, app.setAdj, "too many background");
14436 app.killedBackground = true;
14437 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014438 }
14439 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014440 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14441 // If this is an isolated process, and there are no
14442 // services running in it, then the process is no longer
14443 // needed. We agressively kill these because we can by
14444 // definition not re-use the same process again, and it is
14445 // good to avoid having whatever code was running in them
14446 // left sitting around after no longer needed.
14447 Slog.i(TAG, "Isolated process " + app.processName
14448 + " (pid " + app.pid + ") no longer needed");
14449 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14450 app.processName, app.setAdj, "isolated not needed");
14451 app.killedBackground = true;
14452 Process.killProcessQuiet(app.pid);
14453 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014454 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14455 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14456 && !app.killedBackground) {
14457 numTrimming++;
14458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014459 }
14460 }
14461
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014462 mNumServiceProcs = mNewNumServiceProcs;
14463
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014464 // Now determine the memory trimming level of background processes.
14465 // Unfortunately we need to start at the back of the list to do this
14466 // properly. We only do this if the number of background apps we
14467 // are managing to keep around is less than half the maximum we desire;
14468 // if we are keeping a good number around, we'll let them use whatever
14469 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014470 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014471 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014472 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014473 int minFactor = 2;
14474 if (mHomeProcess != null) minFactor++;
14475 if (mPreviousProcess != null) minFactor++;
14476 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014477 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014478 int fgTrimLevel;
14479 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14480 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14481 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14482 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14483 } else {
14484 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14485 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014486 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014487 for (i=0; i<N; i++) {
14488 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014489 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14490 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014491 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014492 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14493 try {
14494 app.thread.scheduleTrimMemory(curLevel);
14495 } catch (RemoteException e) {
14496 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014497 if (false) {
14498 // For now we won't do this; our memory trimming seems
14499 // to be good enough at this point that destroying
14500 // activities causes more harm than good.
14501 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14502 && app != mHomeProcess && app != mPreviousProcess) {
14503 // For these apps we will also finish their activities
14504 // to help them free memory.
14505 mMainStack.destroyActivitiesLocked(app, false, "trim");
14506 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014507 }
14508 }
14509 app.trimMemoryLevel = curLevel;
14510 step++;
14511 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014512 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014513 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014514 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14515 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014516 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014517 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14518 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014519 break;
14520 }
14521 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014522 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014523 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014524 && app.thread != null) {
14525 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014526 app.thread.scheduleTrimMemory(
14527 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014528 } catch (RemoteException e) {
14529 }
14530 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014531 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014532 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014533 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014534 && app.pendingUiClean) {
14535 // If this application is now in the background and it
14536 // had done UI, then give it the special trim level to
14537 // have it free UI resources.
14538 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14539 if (app.trimMemoryLevel < level && app.thread != null) {
14540 try {
14541 app.thread.scheduleTrimMemory(level);
14542 } catch (RemoteException e) {
14543 }
14544 }
14545 app.pendingUiClean = false;
14546 }
14547 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014548 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014549 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014550 } catch (RemoteException e) {
14551 }
14552 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014553 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014554 }
14555 }
14556 } else {
14557 final int N = mLruProcesses.size();
14558 for (i=0; i<N; i++) {
14559 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014560 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014561 && app.pendingUiClean) {
14562 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14563 && app.thread != null) {
14564 try {
14565 app.thread.scheduleTrimMemory(
14566 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14567 } catch (RemoteException e) {
14568 }
14569 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014570 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014571 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014572 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014573 }
14574 }
14575
14576 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014577 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014579 }
14580
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014581 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014582 synchronized (this) {
14583 int i;
14584
14585 // First remove any unused application processes whose package
14586 // has been removed.
14587 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14588 final ProcessRecord app = mRemovedProcesses.get(i);
14589 if (app.activities.size() == 0
14590 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014591 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014592 TAG, "Exiting empty application process "
14593 + app.processName + " ("
14594 + (app.thread != null ? app.thread.asBinder() : null)
14595 + ")\n");
14596 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014597 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14598 app.processName, app.setAdj, "empty");
14599 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014600 } else {
14601 try {
14602 app.thread.scheduleExit();
14603 } catch (Exception e) {
14604 // Ignore exceptions.
14605 }
14606 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014607 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014608 mRemovedProcesses.remove(i);
14609
14610 if (app.persistent) {
14611 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014612 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014613 }
14614 }
14615 }
14616 }
14617
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014618 // Now update the oom adj for all processes.
14619 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014620 }
14621 }
14622
14623 /** This method sends the specified signal to each of the persistent apps */
14624 public void signalPersistentProcesses(int sig) throws RemoteException {
14625 if (sig != Process.SIGNAL_USR1) {
14626 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14627 }
14628
14629 synchronized (this) {
14630 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14631 != PackageManager.PERMISSION_GRANTED) {
14632 throw new SecurityException("Requires permission "
14633 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14634 }
14635
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014636 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14637 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014638 if (r.thread != null && r.persistent) {
14639 Process.sendSignal(r.pid, sig);
14640 }
14641 }
14642 }
14643 }
14644
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014645 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14646 if (proc == null || proc == mProfileProc) {
14647 proc = mProfileProc;
14648 path = mProfileFile;
14649 profileType = mProfileType;
14650 clearProfilerLocked();
14651 }
14652 if (proc == null) {
14653 return;
14654 }
14655 try {
14656 proc.thread.profilerControl(false, path, null, profileType);
14657 } catch (RemoteException e) {
14658 throw new IllegalStateException("Process disappeared");
14659 }
14660 }
14661
14662 private void clearProfilerLocked() {
14663 if (mProfileFd != null) {
14664 try {
14665 mProfileFd.close();
14666 } catch (IOException e) {
14667 }
14668 }
14669 mProfileApp = null;
14670 mProfileProc = null;
14671 mProfileFile = null;
14672 mProfileType = 0;
14673 mAutoStopProfiler = false;
14674 }
14675
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014676 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014677 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014678
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014679 try {
14680 synchronized (this) {
14681 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14682 // its own permission.
14683 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14684 != PackageManager.PERMISSION_GRANTED) {
14685 throw new SecurityException("Requires permission "
14686 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014687 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014688
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014689 if (start && fd == null) {
14690 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014691 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014692
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014693 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014694 if (process != null) {
14695 try {
14696 int pid = Integer.parseInt(process);
14697 synchronized (mPidsSelfLocked) {
14698 proc = mPidsSelfLocked.get(pid);
14699 }
14700 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014701 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014702
14703 if (proc == null) {
14704 HashMap<String, SparseArray<ProcessRecord>> all
14705 = mProcessNames.getMap();
14706 SparseArray<ProcessRecord> procs = all.get(process);
14707 if (procs != null && procs.size() > 0) {
14708 proc = procs.valueAt(0);
14709 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014710 }
14711 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014712
14713 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014714 throw new IllegalArgumentException("Unknown process: " + process);
14715 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014716
14717 if (start) {
14718 stopProfilerLocked(null, null, 0);
14719 setProfileApp(proc.info, proc.processName, path, fd, false);
14720 mProfileProc = proc;
14721 mProfileType = profileType;
14722 try {
14723 fd = fd.dup();
14724 } catch (IOException e) {
14725 fd = null;
14726 }
14727 proc.thread.profilerControl(start, path, fd, profileType);
14728 fd = null;
14729 mProfileFd = null;
14730 } else {
14731 stopProfilerLocked(proc, path, profileType);
14732 if (fd != null) {
14733 try {
14734 fd.close();
14735 } catch (IOException e) {
14736 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014737 }
14738 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014739
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014740 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014741 }
14742 } catch (RemoteException e) {
14743 throw new IllegalStateException("Process disappeared");
14744 } finally {
14745 if (fd != null) {
14746 try {
14747 fd.close();
14748 } catch (IOException e) {
14749 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014750 }
14751 }
14752 }
Andy McFadden824c5102010-07-09 16:26:57 -070014753
14754 public boolean dumpHeap(String process, boolean managed,
14755 String path, ParcelFileDescriptor fd) throws RemoteException {
14756
14757 try {
14758 synchronized (this) {
14759 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14760 // its own permission (same as profileControl).
14761 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14762 != PackageManager.PERMISSION_GRANTED) {
14763 throw new SecurityException("Requires permission "
14764 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14765 }
14766
14767 if (fd == null) {
14768 throw new IllegalArgumentException("null fd");
14769 }
14770
14771 ProcessRecord proc = null;
14772 try {
14773 int pid = Integer.parseInt(process);
14774 synchronized (mPidsSelfLocked) {
14775 proc = mPidsSelfLocked.get(pid);
14776 }
14777 } catch (NumberFormatException e) {
14778 }
14779
14780 if (proc == null) {
14781 HashMap<String, SparseArray<ProcessRecord>> all
14782 = mProcessNames.getMap();
14783 SparseArray<ProcessRecord> procs = all.get(process);
14784 if (procs != null && procs.size() > 0) {
14785 proc = procs.valueAt(0);
14786 }
14787 }
14788
14789 if (proc == null || proc.thread == null) {
14790 throw new IllegalArgumentException("Unknown process: " + process);
14791 }
14792
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014793 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14794 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014795 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14796 throw new SecurityException("Process not debuggable: " + proc);
14797 }
14798 }
14799
14800 proc.thread.dumpHeap(managed, path, fd);
14801 fd = null;
14802 return true;
14803 }
14804 } catch (RemoteException e) {
14805 throw new IllegalStateException("Process disappeared");
14806 } finally {
14807 if (fd != null) {
14808 try {
14809 fd.close();
14810 } catch (IOException e) {
14811 }
14812 }
14813 }
14814 }
14815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014816 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14817 public void monitor() {
14818 synchronized (this) { }
14819 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014820
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014821 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014822 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14823 ProcessRecord processRecord = mLruProcesses.get(i);
14824 try {
14825 if (processRecord.thread != null) {
14826 processRecord.thread.setCoreSettings(settings);
14827 }
14828 } catch (RemoteException re) {
14829 /* ignore */
14830 }
14831 }
14832 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014833
14834 // Multi-user methods
14835
Amith Yamasani742a6712011-05-04 14:49:28 -070014836 private int mCurrentUserId;
14837 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14838
14839 public boolean switchUser(int userId) {
14840 final int callingUid = Binder.getCallingUid();
14841 if (callingUid != 0 && callingUid != Process.myUid()) {
14842 Slog.e(TAG, "Trying to switch user from unauthorized app");
14843 return false;
14844 }
14845 if (mCurrentUserId == userId)
14846 return true;
14847
14848 synchronized (this) {
14849 // Check if user is already logged in, otherwise check if user exists first before
14850 // adding to the list of logged in users.
14851 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14852 if (!userExists(userId)) {
14853 return false;
14854 }
14855 mLoggedInUsers.append(userId, userId);
14856 }
14857
14858 mCurrentUserId = userId;
14859 boolean haveActivities = mMainStack.switchUser(userId);
14860 if (!haveActivities) {
14861 startHomeActivityLocked(userId);
14862 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014863
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014864 }
Amith Yamasani13593602012-03-22 16:16:17 -070014865
14866 // Inform of user switch
14867 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14868 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14869 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14870
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014871 return true;
14872 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014873
Amith Yamasani52f1d752012-03-28 18:19:29 -070014874 @Override
14875 public UserInfo getCurrentUser() throws RemoteException {
14876 final int callingUid = Binder.getCallingUid();
14877 if (callingUid != 0 && callingUid != Process.myUid()) {
14878 Slog.e(TAG, "Trying to get user from unauthorized app");
14879 return null;
14880 }
14881 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14882 }
14883
Amith Yamasani13593602012-03-22 16:16:17 -070014884 private void onUserRemoved(Intent intent) {
14885 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14886 if (extraUserId < 1) return;
14887
14888 // Kill all the processes for the user
14889 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14890 synchronized (this) {
14891 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14892 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14893 SparseArray<ProcessRecord> uids = uidMap.getValue();
14894 for (int i = 0; i < uids.size(); i++) {
14895 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14896 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14897 }
14898 }
14899 }
14900
14901 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14902 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14903 false, false, true, true, extraUserId);
14904 }
14905 }
14906 }
14907
Amith Yamasani742a6712011-05-04 14:49:28 -070014908 private boolean userExists(int userId) {
14909 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014910 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14911 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014912 } catch (RemoteException re) {
14913 // Won't happen, in same process
14914 }
14915
14916 return false;
14917 }
14918
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014919 private void checkValidCaller(int uid, int userId) {
14920 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14921
14922 throw new SecurityException("Caller uid=" + uid
14923 + " is not privileged to communicate with user=" + userId);
14924 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014925
14926 private int applyUserId(int uid, int userId) {
14927 return UserId.getUid(userId, uid);
14928 }
14929
14930 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014931 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014932 ApplicationInfo newInfo = new ApplicationInfo(info);
14933 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014934 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14935 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014936 return newInfo;
14937 }
14938
14939 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014940 if (aInfo == null
14941 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014942 return aInfo;
14943 }
14944
14945 ActivityInfo info = new ActivityInfo(aInfo);
14946 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14947 return info;
14948 }
14949
14950 static class ServiceMap {
14951
14952 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14953 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14954 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14955 mServicesByIntentPerUser = new SparseArray<
14956 HashMap<Intent.FilterComparison, ServiceRecord>>();
14957
14958 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14959 // TODO: Deal with global services
14960 if (DEBUG_MU)
14961 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14962 return getServices(callingUser).get(name);
14963 }
14964
14965 ServiceRecord getServiceByName(ComponentName name) {
14966 return getServiceByName(name, -1);
14967 }
14968
14969 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14970 // TODO: Deal with global services
14971 if (DEBUG_MU)
14972 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14973 return getServicesByIntent(callingUser).get(filter);
14974 }
14975
14976 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14977 return getServiceByIntent(filter, -1);
14978 }
14979
14980 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14981 // TODO: Deal with global services
14982 getServices(callingUser).put(name, value);
14983 }
14984
14985 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14986 ServiceRecord value) {
14987 // TODO: Deal with global services
14988 getServicesByIntent(callingUser).put(filter, value);
14989 }
14990
14991 void removeServiceByName(ComponentName name, int callingUser) {
14992 // TODO: Deal with global services
14993 ServiceRecord removed = getServices(callingUser).remove(name);
14994 if (DEBUG_MU)
14995 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14996 + " removed=" + removed);
14997 }
14998
14999 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15000 // TODO: Deal with global services
15001 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15002 if (DEBUG_MU)
15003 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15004 + " removed=" + removed);
15005 }
15006
15007 Collection<ServiceRecord> getAllServices(int callingUser) {
15008 // TODO: Deal with global services
15009 return getServices(callingUser).values();
15010 }
15011
15012 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15013 HashMap map = mServicesByNamePerUser.get(callingUser);
15014 if (map == null) {
15015 map = new HashMap<ComponentName, ServiceRecord>();
15016 mServicesByNamePerUser.put(callingUser, map);
15017 }
15018 return map;
15019 }
15020
15021 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15022 int callingUser) {
15023 HashMap map = mServicesByIntentPerUser.get(callingUser);
15024 if (map == null) {
15025 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15026 mServicesByIntentPerUser.put(callingUser, map);
15027 }
15028 return map;
15029 }
15030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015031}