blob: 54ef724df651ade337f56125c2326b34dcc51a21 [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 {
Dianne Hackborna53de062012-05-08 18:53:51 -07001570 if (code == SYSPROPS_TRANSACTION) {
1571 // We need to tell all apps about the system property change.
1572 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1573 synchronized(this) {
1574 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1575 final int NA = apps.size();
1576 for (int ia=0; ia<NA; ia++) {
1577 ProcessRecord app = apps.valueAt(ia);
1578 if (app.thread != null) {
1579 procs.add(app.thread.asBinder());
1580 }
1581 }
1582 }
1583 }
1584
1585 int N = procs.size();
1586 for (int i=0; i<N; i++) {
1587 Parcel data2 = Parcel.obtain();
1588 try {
1589 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1590 } catch (RemoteException e) {
1591 }
1592 data2.recycle();
1593 }
1594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 try {
1596 return super.onTransact(code, data, reply, flags);
1597 } catch (RuntimeException e) {
1598 // The activity manager only throws security exceptions, so let's
1599 // log all others.
1600 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603 throw e;
1604 }
1605 }
1606
1607 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001608 final long now = SystemClock.uptimeMillis();
1609 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1610 return;
1611 }
1612 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1613 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 mProcessStatsThread.notify();
1615 }
1616 }
1617 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 void updateCpuStatsNow() {
1620 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001621 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 final long now = SystemClock.uptimeMillis();
1623 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001626 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1627 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 haveNewCpuStats = true;
1629 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001630 //Slog.i(TAG, mProcessStats.printCurrentState());
1631 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 // + mProcessStats.getTotalCpuPercent() + "%");
1633
Joe Onorato8a9b2202010-02-26 18:56:32 -08001634 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if ("true".equals(SystemProperties.get("events.cpu"))) {
1636 int user = mProcessStats.getLastUserTime();
1637 int system = mProcessStats.getLastSystemTime();
1638 int iowait = mProcessStats.getLastIoWaitTime();
1639 int irq = mProcessStats.getLastIrqTime();
1640 int softIrq = mProcessStats.getLastSoftIrqTime();
1641 int idle = mProcessStats.getLastIdleTime();
1642
1643 int total = user + system + iowait + irq + softIrq + idle;
1644 if (total == 0) total = 1;
1645
Doug Zongker2bec3d42009-12-04 12:52:44 -08001646 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 ((user+system+iowait+irq+softIrq) * 100) / total,
1648 (user * 100) / total,
1649 (system * 100) / total,
1650 (iowait * 100) / total,
1651 (irq * 100) / total,
1652 (softIrq * 100) / total);
1653 }
1654 }
1655
Amith Yamasanie43530a2009-08-21 13:11:37 -07001656 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001657 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001658 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 synchronized(mPidsSelfLocked) {
1660 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001661 if (mOnBattery) {
1662 int perc = bstats.startAddingCpuLocked();
1663 int totalUTime = 0;
1664 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001665 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001667 ProcessStats.Stats st = mProcessStats.getStats(i);
1668 if (!st.working) {
1669 continue;
1670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001672 int otherUTime = (st.rel_utime*perc)/100;
1673 int otherSTime = (st.rel_stime*perc)/100;
1674 totalUTime += otherUTime;
1675 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 if (pr != null) {
1677 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001678 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1679 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001680 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001681 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001682 } else {
1683 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001684 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001685 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001686 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1687 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001688 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001692 bstats.finishAddingCpuLocked(perc, totalUTime,
1693 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 }
1696 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1699 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001700 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
1703 }
1704 }
1705
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001706 @Override
1707 public void batteryNeedsCpuUpdate() {
1708 updateCpuStatsNow();
1709 }
1710
1711 @Override
1712 public void batteryPowerChanged(boolean onBattery) {
1713 // When plugging in, update the CPU stats first before changing
1714 // the plug state.
1715 updateCpuStatsNow();
1716 synchronized (this) {
1717 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001718 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001719 }
1720 }
1721 }
1722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 /**
1724 * Initialize the application bind args. These are passed to each
1725 * process when the bindApplication() IPC is sent to the process. They're
1726 * lazily setup to make sure the services are running when they're asked for.
1727 */
1728 private HashMap<String, IBinder> getCommonServicesLocked() {
1729 if (mAppBindArgs == null) {
1730 mAppBindArgs = new HashMap<String, IBinder>();
1731
1732 // Setup the application init args
1733 mAppBindArgs.put("package", ServiceManager.getService("package"));
1734 mAppBindArgs.put("window", ServiceManager.getService("window"));
1735 mAppBindArgs.put(Context.ALARM_SERVICE,
1736 ServiceManager.getService(Context.ALARM_SERVICE));
1737 }
1738 return mAppBindArgs;
1739 }
1740
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001741 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 if (mFocusedActivity != r) {
1743 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001744 if (r != null) {
1745 mWindowManager.setFocusedApp(r.appToken, true);
1746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748 }
1749
Dianne Hackborn906497c2010-05-10 15:57:38 -07001750 private final void updateLruProcessInternalLocked(ProcessRecord app,
1751 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001753 int lrui = mLruProcesses.indexOf(app);
1754 if (lrui >= 0) mLruProcesses.remove(lrui);
1755
1756 int i = mLruProcesses.size()-1;
1757 int skipTop = 0;
1758
Dianne Hackborn906497c2010-05-10 15:57:38 -07001759 app.lruSeq = mLruSeq;
1760
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001761 // compute the new weight for this process.
1762 if (updateActivityTime) {
1763 app.lastActivityTime = SystemClock.uptimeMillis();
1764 }
1765 if (app.activities.size() > 0) {
1766 // If this process has activities, we more strongly want to keep
1767 // it around.
1768 app.lruWeight = app.lastActivityTime;
1769 } else if (app.pubProviders.size() > 0) {
1770 // If this process contains content providers, we want to keep
1771 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001772 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001773 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001774 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001775 } else {
1776 // If this process doesn't have activities, we less strongly
1777 // want to keep it around, and generally want to avoid getting
1778 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001779 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001780 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001781 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001782 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001783
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001784 while (i >= 0) {
1785 ProcessRecord p = mLruProcesses.get(i);
1786 // If this app shouldn't be in front of the first N background
1787 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001788 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001789 skipTop--;
1790 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001791 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001792 mLruProcesses.add(i+1, app);
1793 break;
1794 }
1795 i--;
1796 }
1797 if (i < 0) {
1798 mLruProcesses.add(0, app);
1799 }
1800
Dianne Hackborn906497c2010-05-10 15:57:38 -07001801 // If the app is currently using a content provider or service,
1802 // bump those processes as well.
1803 if (app.connections.size() > 0) {
1804 for (ConnectionRecord cr : app.connections) {
1805 if (cr.binding != null && cr.binding.service != null
1806 && cr.binding.service.app != null
1807 && cr.binding.service.app.lruSeq != mLruSeq) {
1808 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1809 updateActivityTime, i+1);
1810 }
1811 }
1812 }
1813 if (app.conProviders.size() > 0) {
1814 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001815 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1816 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001817 updateActivityTime, i+1);
1818 }
1819 }
1820 }
1821
Joe Onorato8a9b2202010-02-26 18:56:32 -08001822 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 if (oomAdj) {
1824 updateOomAdjLocked();
1825 }
1826 }
1827
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001828 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001829 boolean oomAdj, boolean updateActivityTime) {
1830 mLruSeq++;
1831 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1832 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001833
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001834 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001836 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001837 // The system gets to run in any process. If there are multiple
1838 // processes with the same uid, just pick the first (this
1839 // should never happen).
1840 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1841 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001842 if (procs == null) return null;
1843 final int N = procs.size();
1844 for (int i = 0; i < N; i++) {
1845 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 }
1848 ProcessRecord proc = mProcessNames.get(processName, uid);
1849 return proc;
1850 }
1851
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001852 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001853 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001854 try {
1855 if (pm.performDexOpt(packageName)) {
1856 mDidDexOpt = true;
1857 }
1858 } catch (RemoteException e) {
1859 }
1860 }
1861
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001862 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 int transit = mWindowManager.getPendingAppTransition();
1864 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1865 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1866 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1867 }
1868
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001869 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001871 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1872 boolean isolated) {
1873 ProcessRecord app;
1874 if (!isolated) {
1875 app = getProcessRecordLocked(processName, info.uid);
1876 } else {
1877 // If this is an isolated process, it can't re-use an existing process.
1878 app = null;
1879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 // We don't have to do anything more if:
1881 // (1) There is an existing application record; and
1882 // (2) The caller doesn't think it is dead, OR there is no thread
1883 // object attached to it so we know it couldn't have crashed; and
1884 // (3) There is a pid assigned to it, so it is either starting or
1885 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001886 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 + " app=" + app + " knownToBeDead=" + knownToBeDead
1888 + " thread=" + (app != null ? app.thread : null)
1889 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001890 if (app != null && app.pid > 0) {
1891 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001892 // We already have the app running, or are waiting for it to
1893 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001894 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001895 // If this is a new package in the process, add the package to the list
1896 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001897 return app;
1898 } else {
1899 // An application record is attached to a previous process,
1900 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001901 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001902 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 String hostingNameStr = hostingName != null
1907 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001908
1909 if (!isolated) {
1910 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1911 // If we are in the background, then check to see if this process
1912 // is bad. If so, we will just silently fail.
1913 if (mBadProcesses.get(info.processName, info.uid) != null) {
1914 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1915 + "/" + info.processName);
1916 return null;
1917 }
1918 } else {
1919 // When the user is explicitly starting a process, then clear its
1920 // crash count so that we won't make it bad until they see at
1921 // least one crash dialog again, and make the process good again
1922 // if it had been bad.
1923 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001924 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001925 mProcessCrashTimes.remove(info.processName, info.uid);
1926 if (mBadProcesses.get(info.processName, info.uid) != null) {
1927 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1928 info.processName);
1929 mBadProcesses.remove(info.processName, info.uid);
1930 if (app != null) {
1931 app.bad = false;
1932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934 }
1935 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001938 app = newProcessRecordLocked(null, info, processName, isolated);
1939 if (app == null) {
1940 Slog.w(TAG, "Failed making new process record for "
1941 + processName + "/" + info.uid + " isolated=" + isolated);
1942 return null;
1943 }
1944 mProcessNames.put(processName, app.uid, app);
1945 if (isolated) {
1946 mIsolatedProcesses.put(app.uid, app);
1947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 } else {
1949 // If this is a new package in the process, add the package to the list
1950 app.addPackage(info.packageName);
1951 }
1952
1953 // If the system is not ready yet, then hold off on starting this
1954 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001955 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001956 && !isAllowedWhileBooting(info)
1957 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (!mProcessesOnHold.contains(app)) {
1959 mProcessesOnHold.add(app);
1960 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001961 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 return app;
1963 }
1964
1965 startProcessLocked(app, hostingType, hostingNameStr);
1966 return (app.pid != 0) ? app : null;
1967 }
1968
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001969 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1970 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1971 }
1972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 private final void startProcessLocked(ProcessRecord app,
1974 String hostingType, String hostingNameStr) {
1975 if (app.pid > 0 && app.pid != MY_PID) {
1976 synchronized (mPidsSelfLocked) {
1977 mPidsSelfLocked.remove(app.pid);
1978 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1979 }
1980 app.pid = 0;
1981 }
1982
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001983 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1984 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 mProcessesOnHold.remove(app);
1986
1987 updateCpuStats();
1988
1989 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1990 mProcDeaths[0] = 0;
1991
1992 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001993 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001996 if (!app.isolated) {
1997 try {
1998 gids = mContext.getPackageManager().getPackageGids(
1999 app.info.packageName);
2000 } catch (PackageManager.NameNotFoundException e) {
2001 Slog.w(TAG, "Unable to retrieve gids", e);
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2005 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2006 && mTopComponent != null
2007 && app.processName.equals(mTopComponent.getPackageName())) {
2008 uid = 0;
2009 }
2010 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2011 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2012 uid = 0;
2013 }
2014 }
2015 int debugFlags = 0;
2016 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2017 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002018 // Also turn on CheckJNI for debuggable apps. It's quite
2019 // awkward to turn on otherwise.
2020 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002022 // Run the app in safe mode if its manifest requests so or the
2023 // system is booted in safe mode.
2024 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2025 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002026 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2029 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2030 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002031 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2032 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 if ("1".equals(SystemProperties.get("debug.assert"))) {
2035 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2036 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002037
2038 // Start the process. It will either succeed and return a result containing
2039 // the PID of the new process, or else throw a RuntimeException.
2040 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002041 app.processName, uid, uid, gids, debugFlags,
2042 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2045 synchronized (bs) {
2046 if (bs.isOnBattery()) {
2047 app.batteryStats.incStartsLocked();
2048 }
2049 }
2050
Jeff Brown3f9dd282011-07-08 20:02:19 -07002051 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 app.processName, hostingType,
2053 hostingNameStr != null ? hostingNameStr : "");
2054
2055 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002056 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
2058
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002059 StringBuilder buf = mStringBuilder;
2060 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 buf.append("Start proc ");
2062 buf.append(app.processName);
2063 buf.append(" for ");
2064 buf.append(hostingType);
2065 if (hostingNameStr != null) {
2066 buf.append(" ");
2067 buf.append(hostingNameStr);
2068 }
2069 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002070 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 buf.append(" uid=");
2072 buf.append(uid);
2073 buf.append(" gids={");
2074 if (gids != null) {
2075 for (int gi=0; gi<gids.length; gi++) {
2076 if (gi != 0) buf.append(", ");
2077 buf.append(gids[gi]);
2078
2079 }
2080 }
2081 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002082 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002083 app.pid = startResult.pid;
2084 app.usingWrapper = startResult.usingWrapper;
2085 app.removed = false;
2086 synchronized (mPidsSelfLocked) {
2087 this.mPidsSelfLocked.put(startResult.pid, app);
2088 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2089 msg.obj = app;
2090 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2091 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093 } catch (RuntimeException e) {
2094 // XXX do better error recovery.
2095 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002096 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 }
2099
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002100 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 if (resumed) {
2102 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2103 } else {
2104 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2105 }
2106 }
2107
Amith Yamasani742a6712011-05-04 14:49:28 -07002108 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002109 if (mHeadless) {
2110 // Added because none of the other calls to ensureBootCompleted seem to fire
2111 // when running headless.
2112 ensureBootCompleted();
2113 return false;
2114 }
2115
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002116 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2117 && mTopAction == null) {
2118 // We are running in factory test mode, but unable to find
2119 // the factory test app, so just sit around displaying the
2120 // error message and don't try to start anything.
2121 return false;
2122 }
2123 Intent intent = new Intent(
2124 mTopAction,
2125 mTopData != null ? Uri.parse(mTopData) : null);
2126 intent.setComponent(mTopComponent);
2127 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2128 intent.addCategory(Intent.CATEGORY_HOME);
2129 }
2130 ActivityInfo aInfo =
2131 intent.resolveActivityInfo(mContext.getPackageManager(),
2132 STOCK_PM_FLAGS);
2133 if (aInfo != null) {
2134 intent.setComponent(new ComponentName(
2135 aInfo.applicationInfo.packageName, aInfo.name));
2136 // Don't do this if the home app is currently being
2137 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002138 aInfo = new ActivityInfo(aInfo);
2139 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002140 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2141 aInfo.applicationInfo.uid);
2142 if (app == null || app.instrumentationClass == null) {
2143 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002144 mMainStack.startActivityLocked(null, intent, null, aInfo,
2145 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002146 }
2147 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002148
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002149 return true;
2150 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002151
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002152 /**
2153 * Starts the "new version setup screen" if appropriate.
2154 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002155 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002156 // Only do this once per boot.
2157 if (mCheckedForSetup) {
2158 return;
2159 }
2160
2161 // We will show this screen if the current one is a different
2162 // version than the last one shown, and we are not running in
2163 // low-level factory test mode.
2164 final ContentResolver resolver = mContext.getContentResolver();
2165 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2166 Settings.Secure.getInt(resolver,
2167 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2168 mCheckedForSetup = true;
2169
2170 // See if we should be showing the platform update setup UI.
2171 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2172 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2173 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2174
2175 // We don't allow third party apps to replace this.
2176 ResolveInfo ri = null;
2177 for (int i=0; ris != null && i<ris.size(); i++) {
2178 if ((ris.get(i).activityInfo.applicationInfo.flags
2179 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2180 ri = ris.get(i);
2181 break;
2182 }
2183 }
2184
2185 if (ri != null) {
2186 String vers = ri.activityInfo.metaData != null
2187 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2188 : null;
2189 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2190 vers = ri.activityInfo.applicationInfo.metaData.getString(
2191 Intent.METADATA_SETUP_VERSION);
2192 }
2193 String lastVers = Settings.Secure.getString(
2194 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2195 if (vers != null && !vers.equals(lastVers)) {
2196 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2197 intent.setComponent(new ComponentName(
2198 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002199 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2200 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002201 }
2202 }
2203 }
2204 }
2205
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002206 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002207 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002208 }
2209
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002210 void enforceNotIsolatedCaller(String caller) {
2211 if (UserId.isIsolated(Binder.getCallingUid())) {
2212 throw new SecurityException("Isolated process not allowed to call " + caller);
2213 }
2214 }
2215
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002216 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002217 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002219 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2220 }
2221 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002222
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002223 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002224 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2225 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002226 synchronized (this) {
2227 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2228 }
2229 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002230
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002231 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002232 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002233 synchronized (this) {
2234 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2235 }
2236 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002237
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002238 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002239 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2240 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002241 synchronized (this) {
2242 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002243 }
2244 }
2245
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002246 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002247 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002248 synchronized (this) {
2249 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2250 }
2251 }
2252
2253 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002254 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2255 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002256 synchronized (this) {
2257 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2258 }
2259 }
2260
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002261 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002262 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002263
2264 final int identHash = System.identityHashCode(r);
2265 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267
Jeff Sharkeya4620792011-05-20 15:29:23 -07002268 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2269 int i = mProcessObservers.beginBroadcast();
2270 while (i > 0) {
2271 i--;
2272 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2273 if (observer != null) {
2274 try {
2275 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2276 } catch (RemoteException e) {
2277 }
2278 }
2279 }
2280 mProcessObservers.finishBroadcast();
2281 }
2282
2283 private void dispatchProcessDied(int pid, int uid) {
2284 int i = mProcessObservers.beginBroadcast();
2285 while (i > 0) {
2286 i--;
2287 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2288 if (observer != null) {
2289 try {
2290 observer.onProcessDied(pid, uid);
2291 } catch (RemoteException e) {
2292 }
2293 }
2294 }
2295 mProcessObservers.finishBroadcast();
2296 }
2297
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002298 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002299 final int N = mPendingActivityLaunches.size();
2300 if (N <= 0) {
2301 return;
2302 }
2303 for (int i=0; i<N; i++) {
2304 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002305 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002306 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002307 }
2308 mPendingActivityLaunches.clear();
2309 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002310
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002311 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002312 Intent intent, String resolvedType, IBinder resultTo,
2313 String resultWho, int requestCode, int startFlags,
2314 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int userId = 0;
2317 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2318 // Requesting home, set the identity to the current user
2319 // HACK!
2320 userId = mCurrentUserId;
2321 } else {
2322 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2323 // the current user's userId
2324 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2325 userId = 0;
2326 } else {
2327 userId = Binder.getOrigCallingUser();
2328 }
2329 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002330 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002331 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2332 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002333 }
2334
2335 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002336 Intent intent, String resolvedType, IBinder resultTo,
2337 String resultWho, int requestCode, int startFlags, String profileFile,
2338 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002339 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002340 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002341 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002342 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002343 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2344 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002345 return res;
2346 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002347
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002348 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002349 Intent intent, String resolvedType, IBinder resultTo,
2350 String resultWho, int requestCode, int startFlags, Configuration config,
2351 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002352 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002353 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002354 resultTo, resultWho, requestCode, startFlags,
2355 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002356 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002357 }
2358
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002359 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002360 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002361 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002362 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002363 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002364 // Refuse possible leaked file descriptors
2365 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2366 throw new IllegalArgumentException("File descriptors passed in Intent");
2367 }
2368
2369 IIntentSender sender = intent.getTarget();
2370 if (!(sender instanceof PendingIntentRecord)) {
2371 throw new IllegalArgumentException("Bad PendingIntent object");
2372 }
2373
2374 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002375
2376 synchronized (this) {
2377 // If this is coming from the currently resumed activity, it is
2378 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002379 if (mMainStack.mResumedActivity != null
2380 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002381 Binder.getCallingUid()) {
2382 mAppSwitchesAllowedTime = 0;
2383 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002384 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002385 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2386 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002387 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002388 }
2389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002391 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 // Refuse possible leaked file descriptors
2393 if (intent != null && intent.hasFileDescriptors() == true) {
2394 throw new IllegalArgumentException("File descriptors passed in Intent");
2395 }
2396
2397 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002398 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2399 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002400 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 return false;
2402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 if (r.app == null || r.app.thread == null) {
2404 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002405 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 return false;
2407 }
2408 intent = new Intent(intent);
2409 // The caller is not allowed to change the data.
2410 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2411 // And we are resetting to find the next component...
2412 intent.setComponent(null);
2413
2414 ActivityInfo aInfo = null;
2415 try {
2416 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002417 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002419 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2420 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421
2422 // Look for the original activity in the list...
2423 final int N = resolves != null ? resolves.size() : 0;
2424 for (int i=0; i<N; i++) {
2425 ResolveInfo rInfo = resolves.get(i);
2426 if (rInfo.activityInfo.packageName.equals(r.packageName)
2427 && rInfo.activityInfo.name.equals(r.info.name)) {
2428 // We found the current one... the next matching is
2429 // after it.
2430 i++;
2431 if (i<N) {
2432 aInfo = resolves.get(i).activityInfo;
2433 }
2434 break;
2435 }
2436 }
2437 } catch (RemoteException e) {
2438 }
2439
2440 if (aInfo == null) {
2441 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002442 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 return false;
2444 }
2445
2446 intent.setComponent(new ComponentName(
2447 aInfo.applicationInfo.packageName, aInfo.name));
2448 intent.setFlags(intent.getFlags()&~(
2449 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2450 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2451 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2452 Intent.FLAG_ACTIVITY_NEW_TASK));
2453
2454 // Okay now we need to start the new activity, replacing the
2455 // currently running activity. This is a little tricky because
2456 // we want to start the new one as if the current one is finished,
2457 // but not finish the current one first so that there is no flicker.
2458 // And thus...
2459 final boolean wasFinishing = r.finishing;
2460 r.finishing = true;
2461
2462 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002463 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 final String resultWho = r.resultWho;
2465 final int requestCode = r.requestCode;
2466 r.resultTo = null;
2467 if (resultTo != null) {
2468 resultTo.removeResultsLocked(r, resultWho, requestCode);
2469 }
2470
2471 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002472 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002473 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2474 resultWho, requestCode, -1, r.launchedFromUid, 0,
2475 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 Binder.restoreCallingIdentity(origId);
2477
2478 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002479 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 return false;
2481 }
2482 return true;
2483 }
2484 }
2485
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002486 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002488 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002489
2490 // This is so super not safe, that only the system (or okay root)
2491 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002492 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002493 final int callingUid = Binder.getCallingUid();
2494 if (callingUid != 0 && callingUid != Process.myUid()) {
2495 throw new SecurityException(
2496 "startActivityInPackage only available to the system");
2497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498
Amith Yamasani742a6712011-05-04 14:49:28 -07002499 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002500 resultTo, resultWho, requestCode, startFlags,
2501 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002502 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002503 }
2504
2505 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002506 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002507 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002508 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002509 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002510 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002511 }
2512
2513 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002514 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2515 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002516
2517 // This is so super not safe, that only the system (or okay root)
2518 // can do it.
2519 final int callingUid = Binder.getCallingUid();
2520 if (callingUid != 0 && callingUid != Process.myUid()) {
2521 throw new SecurityException(
2522 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002524 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002525 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002526 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002531 // Quick case: check if the top-most recent task is the same.
2532 if (N > 0 && mRecentTasks.get(0) == task) {
2533 return;
2534 }
2535 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 for (int i=0; i<N; i++) {
2537 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002538 if (task.userId == tr.userId
2539 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2540 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 mRecentTasks.remove(i);
2542 i--;
2543 N--;
2544 if (task.intent == null) {
2545 // If the new recent task we are adding is not fully
2546 // specified, then replace it with the existing recent task.
2547 task = tr;
2548 }
2549 }
2550 }
2551 if (N >= MAX_RECENT_TASKS) {
2552 mRecentTasks.remove(N-1);
2553 }
2554 mRecentTasks.add(0, task);
2555 }
2556
2557 public void setRequestedOrientation(IBinder token,
2558 int requestedOrientation) {
2559 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002560 ActivityRecord r = mMainStack.isInStackLocked(token);
2561 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 return;
2563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002565 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002567 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002568 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 if (config != null) {
2570 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002571 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002572 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574 }
2575 Binder.restoreCallingIdentity(origId);
2576 }
2577 }
2578
2579 public int getRequestedOrientation(IBinder token) {
2580 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002581 ActivityRecord r = mMainStack.isInStackLocked(token);
2582 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2584 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002585 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587 }
2588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 /**
2590 * This is the internal entry point for handling Activity.finish().
2591 *
2592 * @param token The Binder token referencing the Activity we want to finish.
2593 * @param resultCode Result code, if any, from this Activity.
2594 * @param resultData Result data (Intent), if any, from this Activity.
2595 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002596 * @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 -08002597 */
2598 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2599 // Refuse possible leaked file descriptors
2600 if (resultData != null && resultData.hasFileDescriptors() == true) {
2601 throw new IllegalArgumentException("File descriptors passed in Intent");
2602 }
2603
2604 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002605 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002607 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 if (next != null) {
2609 // ask watcher if this is allowed
2610 boolean resumeOK = true;
2611 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002612 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002614 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
2616
2617 if (!resumeOK) {
2618 return false;
2619 }
2620 }
2621 }
2622 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002623 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 resultData, "app-request");
2625 Binder.restoreCallingIdentity(origId);
2626 return res;
2627 }
2628 }
2629
Dianne Hackborn860755f2010-06-03 18:47:52 -07002630 public final void finishHeavyWeightApp() {
2631 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2632 != PackageManager.PERMISSION_GRANTED) {
2633 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2634 + Binder.getCallingPid()
2635 + ", uid=" + Binder.getCallingUid()
2636 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2637 Slog.w(TAG, msg);
2638 throw new SecurityException(msg);
2639 }
2640
2641 synchronized(this) {
2642 if (mHeavyWeightProcess == null) {
2643 return;
2644 }
2645
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002646 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002647 mHeavyWeightProcess.activities);
2648 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002649 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002650 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002651 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002652 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002653 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002654 null, "finish-heavy");
2655 }
2656 }
2657 }
2658
2659 mHeavyWeightProcess = null;
2660 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2661 }
2662 }
2663
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002664 public void crashApplication(int uid, int initialPid, String packageName,
2665 String message) {
2666 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2667 != PackageManager.PERMISSION_GRANTED) {
2668 String msg = "Permission Denial: crashApplication() from pid="
2669 + Binder.getCallingPid()
2670 + ", uid=" + Binder.getCallingUid()
2671 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2672 Slog.w(TAG, msg);
2673 throw new SecurityException(msg);
2674 }
2675
2676 synchronized(this) {
2677 ProcessRecord proc = null;
2678
2679 // Figure out which process to kill. We don't trust that initialPid
2680 // still has any relation to current pids, so must scan through the
2681 // list.
2682 synchronized (mPidsSelfLocked) {
2683 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2684 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002685 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002686 continue;
2687 }
2688 if (p.pid == initialPid) {
2689 proc = p;
2690 break;
2691 }
2692 for (String str : p.pkgList) {
2693 if (str.equals(packageName)) {
2694 proc = p;
2695 }
2696 }
2697 }
2698 }
2699
2700 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002701 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002702 + " initialPid=" + initialPid
2703 + " packageName=" + packageName);
2704 return;
2705 }
2706
2707 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002708 if (proc.pid == Process.myPid()) {
2709 Log.w(TAG, "crashApplication: trying to crash self!");
2710 return;
2711 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002712 long ident = Binder.clearCallingIdentity();
2713 try {
2714 proc.thread.scheduleCrash(message);
2715 } catch (RemoteException e) {
2716 }
2717 Binder.restoreCallingIdentity(ident);
2718 }
2719 }
2720 }
2721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 public final void finishSubActivity(IBinder token, String resultWho,
2723 int requestCode) {
2724 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002726 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 Binder.restoreCallingIdentity(origId);
2728 }
2729 }
2730
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002731 public boolean finishActivityAffinity(IBinder token) {
2732 synchronized(this) {
2733 final long origId = Binder.clearCallingIdentity();
2734 boolean res = mMainStack.finishActivityAffinityLocked(token);
2735 Binder.restoreCallingIdentity(origId);
2736 return res;
2737 }
2738 }
2739
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002740 public boolean willActivityBeVisible(IBinder token) {
2741 synchronized(this) {
2742 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002743 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2744 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002745 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002746 return true;
2747 }
2748 if (r.fullscreen && !r.finishing) {
2749 return false;
2750 }
2751 }
2752 return true;
2753 }
2754 }
2755
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002756 public void overridePendingTransition(IBinder token, String packageName,
2757 int enterAnim, int exitAnim) {
2758 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002759 ActivityRecord self = mMainStack.isInStackLocked(token);
2760 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002761 return;
2762 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002763
2764 final long origId = Binder.clearCallingIdentity();
2765
2766 if (self.state == ActivityState.RESUMED
2767 || self.state == ActivityState.PAUSING) {
2768 mWindowManager.overridePendingAppTransition(packageName,
2769 enterAnim, exitAnim);
2770 }
2771
2772 Binder.restoreCallingIdentity(origId);
2773 }
2774 }
2775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 * Main function for removing an existing process from the activity manager
2778 * as a result of that process going away. Clears out all connections
2779 * to the process.
2780 */
2781 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002782 boolean restarting, boolean allowRestart) {
2783 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002785 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 }
2787
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002788 if (mProfileProc == app) {
2789 clearProfilerLocked();
2790 }
2791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002793 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2794 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2795 mMainStack.mPausingActivity = null;
2796 }
2797 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2798 mMainStack.mLastPausedActivity = null;
2799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800
2801 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002802 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803
2804 boolean atTop = true;
2805 boolean hasVisibleActivities = false;
2806
2807 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002808 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002809 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 TAG, "Removing app " + app + " from history with " + i + " entries");
2811 while (i > 0) {
2812 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002813 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002814 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2816 if (r.app == app) {
2817 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002818 if (ActivityStack.DEBUG_ADD_REMOVE) {
2819 RuntimeException here = new RuntimeException("here");
2820 here.fillInStackTrace();
2821 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2822 + ": haveState=" + r.haveState
2823 + " stateNotNeeded=" + r.stateNotNeeded
2824 + " finishing=" + r.finishing
2825 + " state=" + r.state, here);
2826 }
2827 if (!r.finishing) {
2828 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002829 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2830 System.identityHashCode(r),
2831 r.task.taskId, r.shortComponentName,
2832 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002833 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002834 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835
2836 } else {
2837 // We have the current state for this activity, so
2838 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002839 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 TAG, "Keeping entry, setting app to null");
2841 if (r.visible) {
2842 hasVisibleActivities = true;
2843 }
2844 r.app = null;
2845 r.nowVisible = false;
2846 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002847 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2848 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 r.icicle = null;
2850 }
2851 }
2852
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002853 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 }
2855 atTop = false;
2856 }
2857
2858 app.activities.clear();
2859
2860 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002861 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 + " running instrumentation " + app.instrumentationClass);
2863 Bundle info = new Bundle();
2864 info.putString("shortMsg", "Process crashed.");
2865 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2866 }
2867
2868 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002869 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 // If there was nothing to resume, and we are not already
2871 // restarting this process, but there is a visible activity that
2872 // is hosted by the process... then make sure all visible
2873 // activities are running, taking care of restarting this
2874 // process.
2875 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002876 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 }
2878 }
2879 }
2880 }
2881
2882 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2883 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002885 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2886 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2888 return i;
2889 }
2890 }
2891 return -1;
2892 }
2893
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002894 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 IApplicationThread thread) {
2896 if (thread == null) {
2897 return null;
2898 }
2899
2900 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002901 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
2903
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002904 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 IApplicationThread thread) {
2906
2907 mProcDeaths[0]++;
2908
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002909 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2910 synchronized (stats) {
2911 stats.noteProcessDiedLocked(app.info.uid, pid);
2912 }
2913
Magnus Edlund7bb25812010-02-24 15:45:06 +01002914 // Clean up already done if the process has been re-started.
2915 if (app.pid == pid && app.thread != null &&
2916 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002917 if (!app.killedBackground) {
2918 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2919 + ") has died.");
2920 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002921 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002922 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 TAG, "Dying app: " + app + ", pid: " + pid
2924 + ", thread: " + thread.asBinder());
2925 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002926 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927
2928 if (doLowMem) {
2929 // If there are no longer any background processes running,
2930 // and the app that died was not running instrumentation,
2931 // then tell everyone we are now low on memory.
2932 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002933 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2934 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002935 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 haveBg = true;
2937 break;
2938 }
2939 }
2940
2941 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002942 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002943 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002944 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2945 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002946 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002947 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2948 // The low memory report is overriding any current
2949 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002950 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002951 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002952 rec.lastRequestedGc = 0;
2953 } else {
2954 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002956 rec.reportLowMemory = true;
2957 rec.lastLowMemory = now;
2958 mProcessesToGc.remove(rec);
2959 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
2961 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002962 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002963 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 }
2965 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002966 } else if (app.pid != pid) {
2967 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002968 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002969 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002970 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002971 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002972 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 + thread.asBinder());
2974 }
2975 }
2976
Dan Egnor42471dd2010-01-07 17:25:22 -08002977 /**
2978 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002979 * @param clearTraces causes the dump file to be erased prior to the new
2980 * traces being written, if true; when false, the new traces will be
2981 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002982 * @param firstPids of dalvik VM processes to dump stack traces for first
2983 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002984 * @return file containing stack traces, or null if no dump file is configured
2985 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002986 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2987 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002988 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2989 if (tracesPath == null || tracesPath.length() == 0) {
2990 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002992
2993 File tracesFile = new File(tracesPath);
2994 try {
2995 File tracesDir = tracesFile.getParentFile();
2996 if (!tracesDir.exists()) tracesFile.mkdirs();
2997 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2998
Christopher Tate6ee412d2010-05-28 12:01:56 -07002999 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003000 tracesFile.createNewFile();
3001 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3002 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003003 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003004 return null;
3005 }
3006
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003007 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
3008 return tracesFile;
3009 }
3010
3011 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
3012 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003013 // Use a FileObserver to detect when traces finish writing.
3014 // The order of traces is considered important to maintain for legibility.
3015 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3016 public synchronized void onEvent(int event, String path) { notify(); }
3017 };
3018
3019 try {
3020 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003021
3022 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003023 if (firstPids != null) {
3024 try {
3025 int num = firstPids.size();
3026 for (int i = 0; i < num; i++) {
3027 synchronized (observer) {
3028 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3029 observer.wait(200); // Wait for write-close, give up after 200msec
3030 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003031 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003032 } catch (InterruptedException e) {
3033 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003034 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003035 }
3036
3037 // Next measure CPU usage.
3038 if (processStats != null) {
3039 processStats.init();
3040 System.gc();
3041 processStats.update();
3042 try {
3043 synchronized (processStats) {
3044 processStats.wait(500); // measure over 1/2 second.
3045 }
3046 } catch (InterruptedException e) {
3047 }
3048 processStats.update();
3049
3050 // We'll take the stack crawls of just the top apps using CPU.
3051 final int N = processStats.countWorkingStats();
3052 int numProcs = 0;
3053 for (int i=0; i<N && numProcs<5; i++) {
3054 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3055 if (lastPids.indexOfKey(stats.pid) >= 0) {
3056 numProcs++;
3057 try {
3058 synchronized (observer) {
3059 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3060 observer.wait(200); // Wait for write-close, give up after 200msec
3061 }
3062 } catch (InterruptedException e) {
3063 Log.wtf(TAG, e);
3064 }
3065
3066 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003067 }
3068 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003069
Dan Egnor42471dd2010-01-07 17:25:22 -08003070 } finally {
3071 observer.stopWatching();
3072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 }
3074
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003075 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003076 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003077 return;
3078 }
3079 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3080 if (tracesPath == null || tracesPath.length() == 0) {
3081 return;
3082 }
3083
3084 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3085 StrictMode.allowThreadDiskWrites();
3086 try {
3087 final File tracesFile = new File(tracesPath);
3088 final File tracesDir = tracesFile.getParentFile();
3089 final File tracesTmp = new File(tracesDir, "__tmp__");
3090 try {
3091 if (!tracesDir.exists()) tracesFile.mkdirs();
3092 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3093
3094 if (tracesFile.exists()) {
3095 tracesTmp.delete();
3096 tracesFile.renameTo(tracesTmp);
3097 }
3098 StringBuilder sb = new StringBuilder();
3099 Time tobj = new Time();
3100 tobj.set(System.currentTimeMillis());
3101 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3102 sb.append(": ");
3103 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3104 sb.append(" since ");
3105 sb.append(msg);
3106 FileOutputStream fos = new FileOutputStream(tracesFile);
3107 fos.write(sb.toString().getBytes());
3108 if (app == null) {
3109 fos.write("\n*** No application process!".getBytes());
3110 }
3111 fos.close();
3112 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3113 } catch (IOException e) {
3114 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3115 return;
3116 }
3117
3118 if (app != null) {
3119 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3120 firstPids.add(app.pid);
3121 dumpStackTraces(tracesPath, firstPids, null, null);
3122 }
3123
3124 File lastTracesFile = null;
3125 File curTracesFile = null;
3126 for (int i=9; i>=0; i--) {
3127 String name = String.format("slow%02d.txt", i);
3128 curTracesFile = new File(tracesDir, name);
3129 if (curTracesFile.exists()) {
3130 if (lastTracesFile != null) {
3131 curTracesFile.renameTo(lastTracesFile);
3132 } else {
3133 curTracesFile.delete();
3134 }
3135 }
3136 lastTracesFile = curTracesFile;
3137 }
3138 tracesFile.renameTo(curTracesFile);
3139 if (tracesTmp.exists()) {
3140 tracesTmp.renameTo(tracesFile);
3141 }
3142 } finally {
3143 StrictMode.setThreadPolicy(oldPolicy);
3144 }
3145 }
3146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003147 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3148 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003149 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3150 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3151
Dianne Hackborn287952c2010-09-22 22:34:31 -07003152 if (mController != null) {
3153 try {
3154 // 0 == continue, -1 = kill process immediately
3155 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3156 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3157 } catch (RemoteException e) {
3158 mController = null;
3159 }
3160 }
3161
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003162 long anrTime = SystemClock.uptimeMillis();
3163 if (MONITOR_CPU_USAGE) {
3164 updateCpuStatsNow();
3165 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003166
3167 synchronized (this) {
3168 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3169 if (mShuttingDown) {
3170 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3171 return;
3172 } else if (app.notResponding) {
3173 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3174 return;
3175 } else if (app.crashing) {
3176 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3177 return;
3178 }
3179
3180 // In case we come through here for the same app before completing
3181 // this one, mark as anring now so we will bail out.
3182 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003183
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003184 // Log the ANR to the event log.
3185 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3186 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003187
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003188 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003189 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003190
3191 int parentPid = app.pid;
3192 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003193 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003194
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003195 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003196
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003197 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3198 ProcessRecord r = mLruProcesses.get(i);
3199 if (r != null && r.thread != null) {
3200 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003201 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3202 if (r.persistent) {
3203 firstPids.add(pid);
3204 } else {
3205 lastPids.put(pid, Boolean.TRUE);
3206 }
3207 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
3210 }
3211
Dan Egnor42471dd2010-01-07 17:25:22 -08003212 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003213 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003214 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003215 info.append("ANR in ").append(app.processName);
3216 if (activity != null && activity.shortComponentName != null) {
3217 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003218 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003219 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003221 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003223 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003224 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226
Dianne Hackborn287952c2010-09-22 22:34:31 -07003227 final ProcessStats processStats = new ProcessStats(true);
3228
3229 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3230
Dan Egnor42471dd2010-01-07 17:25:22 -08003231 String cpuInfo = null;
3232 if (MONITOR_CPU_USAGE) {
3233 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003234 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003235 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003236 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003237 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003238 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 }
3240
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003241 info.append(processStats.printCurrentState(anrTime));
3242
Joe Onorato8a9b2202010-02-26 18:56:32 -08003243 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003244 if (tracesFile == null) {
3245 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3246 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3247 }
3248
Jeff Sharkeya353d262011-10-28 11:12:06 -07003249 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3250 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003251
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003252 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003254 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3255 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003257 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3258 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 }
3260 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003261 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263 }
3264
Dan Egnor42471dd2010-01-07 17:25:22 -08003265 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3266 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3267 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003268
3269 synchronized (this) {
3270 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003271 Slog.w(TAG, "Killing " + app + ": background ANR");
3272 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3273 app.processName, app.setAdj, "background ANR");
3274 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003275 return;
3276 }
3277
3278 // Set the app's notResponding state, and look up the errorReportReceiver
3279 makeAppNotRespondingLocked(app,
3280 activity != null ? activity.shortComponentName : null,
3281 annotation != null ? "ANR " + annotation : "ANR",
3282 info.toString());
3283
3284 // Bring up the infamous App Not Responding dialog
3285 Message msg = Message.obtain();
3286 HashMap map = new HashMap();
3287 msg.what = SHOW_NOT_RESPONDING_MSG;
3288 msg.obj = map;
3289 map.put("app", app);
3290 if (activity != null) {
3291 map.put("activity", activity);
3292 }
3293
3294 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
3297
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003298 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3299 if (!mLaunchWarningShown) {
3300 mLaunchWarningShown = true;
3301 mHandler.post(new Runnable() {
3302 @Override
3303 public void run() {
3304 synchronized (ActivityManagerService.this) {
3305 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3306 d.show();
3307 mHandler.postDelayed(new Runnable() {
3308 @Override
3309 public void run() {
3310 synchronized (ActivityManagerService.this) {
3311 d.dismiss();
3312 mLaunchWarningShown = false;
3313 }
3314 }
3315 }, 4000);
3316 }
3317 }
3318 });
3319 }
3320 }
3321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003323 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003324 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 int uid = Binder.getCallingUid();
3326 int pid = Binder.getCallingPid();
3327 long callingId = Binder.clearCallingIdentity();
3328 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003329 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 int pkgUid = -1;
3331 synchronized(this) {
3332 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003333 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 } catch (RemoteException e) {
3335 }
3336 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003337 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 return false;
3339 }
3340 if (uid == pkgUid || checkComponentPermission(
3341 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003342 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003344 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 } else {
3346 throw new SecurityException(pid+" does not have permission:"+
3347 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3348 "for process:"+packageName);
3349 }
3350 }
3351
3352 try {
3353 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003354 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3356 Uri.fromParts("package", packageName, null));
3357 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003358 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003359 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 } catch (RemoteException e) {
3361 }
3362 } finally {
3363 Binder.restoreCallingIdentity(callingId);
3364 }
3365 return true;
3366 }
3367
Dianne Hackborn03abb812010-01-04 18:43:19 -08003368 public void killBackgroundProcesses(final String packageName) {
3369 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3370 != PackageManager.PERMISSION_GRANTED &&
3371 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3372 != PackageManager.PERMISSION_GRANTED) {
3373 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 + Binder.getCallingPid()
3375 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003376 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003377 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 throw new SecurityException(msg);
3379 }
3380
Amith Yamasani483f3b02012-03-13 16:08:00 -07003381 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 long callingId = Binder.clearCallingIdentity();
3383 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003384 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 int pkgUid = -1;
3386 synchronized(this) {
3387 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003388 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 } catch (RemoteException e) {
3390 }
3391 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003392 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 return;
3394 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003395 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003396 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3397 }
3398 } finally {
3399 Binder.restoreCallingIdentity(callingId);
3400 }
3401 }
3402
3403 public void killAllBackgroundProcesses() {
3404 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3405 != PackageManager.PERMISSION_GRANTED) {
3406 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3407 + Binder.getCallingPid()
3408 + ", uid=" + Binder.getCallingUid()
3409 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3410 Slog.w(TAG, msg);
3411 throw new SecurityException(msg);
3412 }
3413
3414 long callingId = Binder.clearCallingIdentity();
3415 try {
3416 synchronized(this) {
3417 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3418 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3419 final int NA = apps.size();
3420 for (int ia=0; ia<NA; ia++) {
3421 ProcessRecord app = apps.valueAt(ia);
3422 if (app.persistent) {
3423 // we don't kill persistent processes
3424 continue;
3425 }
3426 if (app.removed) {
3427 procs.add(app);
3428 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3429 app.removed = true;
3430 procs.add(app);
3431 }
3432 }
3433 }
3434
3435 int N = procs.size();
3436 for (int i=0; i<N; i++) {
3437 removeProcessLocked(procs.get(i), false, true, "kill all background");
3438 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003439 }
3440 } finally {
3441 Binder.restoreCallingIdentity(callingId);
3442 }
3443 }
3444
3445 public void forceStopPackage(final String packageName) {
3446 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3447 != PackageManager.PERMISSION_GRANTED) {
3448 String msg = "Permission Denial: forceStopPackage() from pid="
3449 + Binder.getCallingPid()
3450 + ", uid=" + Binder.getCallingUid()
3451 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003452 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003453 throw new SecurityException(msg);
3454 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003455 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003456 long callingId = Binder.clearCallingIdentity();
3457 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003458 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003459 int pkgUid = -1;
3460 synchronized(this) {
3461 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003462 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003463 } catch (RemoteException e) {
3464 }
3465 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003466 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003467 return;
3468 }
3469 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003470 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003471 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003472 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003473 } catch (IllegalArgumentException e) {
3474 Slog.w(TAG, "Failed trying to unstop package "
3475 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 }
3478 } finally {
3479 Binder.restoreCallingIdentity(callingId);
3480 }
3481 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003482
3483 /*
3484 * The pkg name and uid have to be specified.
3485 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3486 */
3487 public void killApplicationWithUid(String pkg, int uid) {
3488 if (pkg == null) {
3489 return;
3490 }
3491 // Make sure the uid is valid.
3492 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003493 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003494 return;
3495 }
3496 int callerUid = Binder.getCallingUid();
3497 // Only the system server can kill an application
3498 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003499 // Post an aysnc message to kill the application
3500 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3501 msg.arg1 = uid;
3502 msg.arg2 = 0;
3503 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003504 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003505 } else {
3506 throw new SecurityException(callerUid + " cannot kill pkg: " +
3507 pkg);
3508 }
3509 }
3510
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003511 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003512 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003513 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003514 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003515 if (reason != null) {
3516 intent.putExtra("reason", reason);
3517 }
3518
3519 final int uid = Binder.getCallingUid();
3520 final long origId = Binder.clearCallingIdentity();
3521 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003522 mWindowManager.closeSystemDialogs(reason);
3523
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003524 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003525 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003526 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003527 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003528 Activity.RESULT_CANCELED, null, "close-sys");
3529 }
3530 }
3531
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003532 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003533 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003534 }
3535 Binder.restoreCallingIdentity(origId);
3536 }
3537
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003538 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003539 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003540 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003541 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3542 for (int i=pids.length-1; i>=0; i--) {
3543 infos[i] = new Debug.MemoryInfo();
3544 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003545 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003546 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003547 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003548
Dianne Hackbornb437e092011-08-05 17:50:29 -07003549 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003550 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003551 long[] pss = new long[pids.length];
3552 for (int i=pids.length-1; i>=0; i--) {
3553 pss[i] = Debug.getPss(pids[i]);
3554 }
3555 return pss;
3556 }
3557
Christopher Tate5e1ab332009-09-01 20:32:49 -07003558 public void killApplicationProcess(String processName, int uid) {
3559 if (processName == null) {
3560 return;
3561 }
3562
3563 int callerUid = Binder.getCallingUid();
3564 // Only the system server can kill an application
3565 if (callerUid == Process.SYSTEM_UID) {
3566 synchronized (this) {
3567 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003568 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003569 try {
3570 app.thread.scheduleSuicide();
3571 } catch (RemoteException e) {
3572 // If the other end already died, then our work here is done.
3573 }
3574 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003575 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003576 + processName + " / " + uid);
3577 }
3578 }
3579 } else {
3580 throw new SecurityException(callerUid + " cannot kill app process: " +
3581 processName);
3582 }
3583 }
3584
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003586 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3588 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003589 if (!mProcessesReady) {
3590 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 intent.putExtra(Intent.EXTRA_UID, uid);
3593 broadcastIntentLocked(null, null, intent,
3594 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003595 false, false,
3596 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 }
3598
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003599 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003600 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003601 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003602 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603
Dianne Hackborn03abb812010-01-04 18:43:19 -08003604 // Remove all processes this package may have touched: all with the
3605 // same UID (except for the system or root user), and all whose name
3606 // matches the package name.
3607 final String procNamePrefix = packageName + ":";
3608 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3609 final int NA = apps.size();
3610 for (int ia=0; ia<NA; ia++) {
3611 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003612 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003613 // we don't kill persistent processes
3614 continue;
3615 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003616 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003617 if (doit) {
3618 procs.add(app);
3619 }
Amith Yamasani13593602012-03-22 16:16:17 -07003620 // If uid is specified and the uid and process name match
3621 // Or, the uid is not specified and the process name matches
3622 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003623 || ((app.processName.equals(packageName)
3624 || app.processName.startsWith(procNamePrefix))
3625 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003626 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003627 if (!doit) {
3628 return true;
3629 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003630 app.removed = true;
3631 procs.add(app);
3632 }
3633 }
3634 }
3635 }
3636
3637 int N = procs.size();
3638 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003639 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003640 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003641 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003642 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003643
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003644 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003645 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003646 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003647 int i;
3648 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 if (uid < 0) {
3651 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003652 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 } catch (RemoteException e) {
3654 }
3655 }
3656
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003657 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003658 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003659
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003660 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3661 while (badApps.hasNext()) {
3662 SparseArray<Long> ba = badApps.next();
3663 if (ba.get(uid) != null) {
3664 badApps.remove();
3665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 }
3667 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003668
3669 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003670 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003672 TaskRecord lastTask = null;
3673 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003674 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003675 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003676 if (r.userId == userId
3677 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003678 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003679 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003680 if (r.finishing) {
3681 // If this activity is just finishing, then it is not
3682 // interesting as far as something to stop.
3683 continue;
3684 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003685 return true;
3686 }
3687 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003688 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003689 if (samePackage) {
3690 if (r.app != null) {
3691 r.app.removed = true;
3692 }
3693 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003695 lastTask = r.task;
3696 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003697 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003698 i--;
3699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 }
3701 }
3702
3703 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003704 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003705 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003706 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003707 if (!doit) {
3708 return true;
3709 }
3710 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003711 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 if (service.app != null) {
3713 service.app.removed = true;
3714 }
3715 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003716 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 services.add(service);
3718 }
3719 }
3720
3721 N = services.size();
3722 for (i=0; i<N; i++) {
3723 bringDownServiceLocked(services.get(i), true);
3724 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003725
3726 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003727 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003728 if (provider.info.packageName.equals(name)
3729 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3730 if (!doit) {
3731 return true;
3732 }
3733 didSomething = true;
3734 providers.add(provider);
3735 }
3736 }
3737
3738 N = providers.size();
3739 for (i=0; i<N; i++) {
3740 removeDyingProviderLocked(null, providers.get(i));
3741 }
3742
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003743 if (doit) {
3744 if (purgeCache) {
3745 AttributeCache ac = AttributeCache.instance();
3746 if (ac != null) {
3747 ac.removePackage(name);
3748 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003749 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003750 if (mBooted) {
3751 mMainStack.resumeTopActivityLocked(null);
3752 mMainStack.scheduleIdleLocked();
3753 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003754 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003755
3756 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 }
3758
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003759 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003760 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003762 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003763 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003764 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 + "/" + uid + ")");
3766
3767 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003768 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003769 if (mHeavyWeightProcess == app) {
3770 mHeavyWeightProcess = null;
3771 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 boolean needRestart = false;
3774 if (app.pid > 0 && app.pid != MY_PID) {
3775 int pid = app.pid;
3776 synchronized (mPidsSelfLocked) {
3777 mPidsSelfLocked.remove(pid);
3778 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3779 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003780 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003781 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003782 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003783 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003785 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003787 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 } else {
3789 needRestart = true;
3790 }
3791 }
3792 } else {
3793 mRemovedProcesses.add(app);
3794 }
3795
3796 return needRestart;
3797 }
3798
3799 private final void processStartTimedOutLocked(ProcessRecord app) {
3800 final int pid = app.pid;
3801 boolean gone = false;
3802 synchronized (mPidsSelfLocked) {
3803 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3804 if (knownApp != null && knownApp.thread == null) {
3805 mPidsSelfLocked.remove(pid);
3806 gone = true;
3807 }
3808 }
3809
3810 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003811 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003812 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003813 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003814 mProcessNames.remove(app.processName, app.uid);
3815 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003816 if (mHeavyWeightProcess == app) {
3817 mHeavyWeightProcess = null;
3818 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3819 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003820 // Take care of any launching providers waiting for this process.
3821 checkAppInLaunchingProvidersLocked(app, true);
3822 // Take care of any services that are waiting for the process.
3823 for (int i=0; i<mPendingServices.size(); i++) {
3824 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003825 if ((app.uid == sr.appInfo.uid
3826 && app.processName.equals(sr.processName))
3827 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003828 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003829 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003830 mPendingServices.remove(i);
3831 i--;
3832 bringDownServiceLocked(sr, true);
3833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003835 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3836 app.processName, app.setAdj, "start timeout");
3837 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003838 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003839 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003840 try {
3841 IBackupManager bm = IBackupManager.Stub.asInterface(
3842 ServiceManager.getService(Context.BACKUP_SERVICE));
3843 bm.agentDisconnected(app.info.packageName);
3844 } catch (RemoteException e) {
3845 // Can't happen; the backup manager is local
3846 }
3847 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003848 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003849 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003850 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003853 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 }
3855 }
3856
3857 private final boolean attachApplicationLocked(IApplicationThread thread,
3858 int pid) {
3859
3860 // Find the application record that is being attached... either via
3861 // the pid if we are running in multiple processes, or just pull the
3862 // next app record if we are emulating process with anonymous threads.
3863 ProcessRecord app;
3864 if (pid != MY_PID && pid >= 0) {
3865 synchronized (mPidsSelfLocked) {
3866 app = mPidsSelfLocked.get(pid);
3867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 } else {
3869 app = null;
3870 }
3871
3872 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003873 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003875 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003877 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 } else {
3879 try {
3880 thread.scheduleExit();
3881 } catch (Exception e) {
3882 // Ignore exceptions.
3883 }
3884 }
3885 return false;
3886 }
3887
3888 // If this application record is still attached to a previous
3889 // process, clean it up now.
3890 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003891 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 }
3893
3894 // Tell the process all about itself.
3895
Joe Onorato8a9b2202010-02-26 18:56:32 -08003896 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 TAG, "Binding process pid " + pid + " to record " + app);
3898
3899 String processName = app.processName;
3900 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003901 AppDeathRecipient adr = new AppDeathRecipient(
3902 app, pid, thread);
3903 thread.asBinder().linkToDeath(adr, 0);
3904 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 } catch (RemoteException e) {
3906 app.resetPackageList();
3907 startProcessLocked(app, "link fail", processName);
3908 return false;
3909 }
3910
Doug Zongker2bec3d42009-12-04 12:52:44 -08003911 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912
3913 app.thread = thread;
3914 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003915 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3916 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 app.forcingToForeground = null;
3918 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003919 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 app.debugging = false;
3921
3922 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3923
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003924 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003925 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003927 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003928 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003929 }
3930
Joe Onorato8a9b2202010-02-26 18:56:32 -08003931 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 TAG, "New app record " + app
3933 + " thread=" + thread.asBinder() + " pid=" + pid);
3934 try {
3935 int testMode = IApplicationThread.DEBUG_OFF;
3936 if (mDebugApp != null && mDebugApp.equals(processName)) {
3937 testMode = mWaitForDebugger
3938 ? IApplicationThread.DEBUG_WAIT
3939 : IApplicationThread.DEBUG_ON;
3940 app.debugging = true;
3941 if (mDebugTransient) {
3942 mDebugApp = mOrigDebugApp;
3943 mWaitForDebugger = mOrigWaitForDebugger;
3944 }
3945 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003946 String profileFile = app.instrumentationProfileFile;
3947 ParcelFileDescriptor profileFd = null;
3948 boolean profileAutoStop = false;
3949 if (mProfileApp != null && mProfileApp.equals(processName)) {
3950 mProfileProc = app;
3951 profileFile = mProfileFile;
3952 profileFd = mProfileFd;
3953 profileAutoStop = mAutoStopProfiler;
3954 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003955 boolean enableOpenGlTrace = false;
3956 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3957 enableOpenGlTrace = true;
3958 mOpenGlTraceApp = null;
3959 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003960
Christopher Tate181fafa2009-05-14 11:12:14 -07003961 // If the app is being launched for restore or full backup, set it up specially
3962 boolean isRestrictedBackupMode = false;
3963 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3964 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003965 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003966 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3967 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003968
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003969 ensurePackageDexOpt(app.instrumentationInfo != null
3970 ? app.instrumentationInfo.packageName
3971 : app.info.packageName);
3972 if (app.instrumentationClass != null) {
3973 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003974 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003975 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003976 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003977 ApplicationInfo appInfo = app.instrumentationInfo != null
3978 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003979 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003980 if (profileFd != null) {
3981 profileFd = profileFd.dup();
3982 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003983 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003984 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003985 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3986 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003987 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003988 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003989 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003990 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 } catch (Exception e) {
3992 // todo: Yikes! What should we do? For now we will try to
3993 // start another process, but that could easily get us in
3994 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003995 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996
3997 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003998 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 startProcessLocked(app, "bind fail", processName);
4000 return false;
4001 }
4002
4003 // Remove this record from the list of starting applications.
4004 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004005 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4006 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 mProcessesOnHold.remove(app);
4008
4009 boolean badApp = false;
4010 boolean didSomething = false;
4011
4012 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004013 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004014 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004015 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 && processName.equals(hr.processName)) {
4017 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004018 if (mHeadless) {
4019 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4020 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 didSomething = true;
4022 }
4023 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004024 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 + hr.intent.getComponent().flattenToShortString(), e);
4026 badApp = true;
4027 }
4028 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004029 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031 }
4032
4033 // Find any services that should be running in this process...
4034 if (!badApp && mPendingServices.size() > 0) {
4035 ServiceRecord sr = null;
4036 try {
4037 for (int i=0; i<mPendingServices.size(); i++) {
4038 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004039 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4040 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 continue;
4042 }
4043
4044 mPendingServices.remove(i);
4045 i--;
4046 realStartServiceLocked(sr, app);
4047 didSomething = true;
4048 }
4049 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004050 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 + sr.shortName, e);
4052 badApp = true;
4053 }
4054 }
4055
Christopher Tatef46723b2012-01-26 14:19:24 -08004056 // Check if a next-broadcast receiver is in this process...
4057 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004059 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004061 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 }
4064 }
4065
Christopher Tate181fafa2009-05-14 11:12:14 -07004066 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004067 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004068 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004069 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004070 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004071 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4072 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4073 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004074 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004075 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004076 e.printStackTrace();
4077 }
4078 }
4079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 if (badApp) {
4081 // todo: Also need to kill application to deal with all
4082 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004083 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 return false;
4085 }
4086
4087 if (!didSomething) {
4088 updateOomAdjLocked();
4089 }
4090
4091 return true;
4092 }
4093
4094 public final void attachApplication(IApplicationThread thread) {
4095 synchronized (this) {
4096 int callingPid = Binder.getCallingPid();
4097 final long origId = Binder.clearCallingIdentity();
4098 attachApplicationLocked(thread, callingPid);
4099 Binder.restoreCallingIdentity(origId);
4100 }
4101 }
4102
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004103 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004105 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4106 if (stopProfiling) {
4107 synchronized (this) {
4108 if (mProfileProc == r.app) {
4109 if (mProfileFd != null) {
4110 try {
4111 mProfileFd.close();
4112 } catch (IOException e) {
4113 }
4114 clearProfilerLocked();
4115 }
4116 }
4117 }
4118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 Binder.restoreCallingIdentity(origId);
4120 }
4121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004123 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004124 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004126
4127 synchronized (this) {
4128 updateEventDispatchingLocked();
4129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 }
4131
Dianne Hackborn661cd522011-08-22 00:26:20 -07004132 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004133 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004134 mWindowManager.showBootMessage(msg, always);
4135 }
4136
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004137 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004138 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004139 final long token = Binder.clearCallingIdentity();
4140 try {
4141 synchronized (this) {
4142 if (mLockScreenShown) {
4143 mLockScreenShown = false;
4144 comeOutOfSleepIfNeededLocked();
4145 }
4146 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004147 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004148 } finally {
4149 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004150 }
4151 }
4152
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004153 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004154 IntentFilter pkgFilter = new IntentFilter();
4155 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4156 pkgFilter.addDataScheme("package");
4157 mContext.registerReceiver(new BroadcastReceiver() {
4158 @Override
4159 public void onReceive(Context context, Intent intent) {
4160 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4161 if (pkgs != null) {
4162 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004163 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004164 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4165 setResultCode(Activity.RESULT_OK);
4166 return;
4167 }
4168 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004169 }
4170 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004171 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004172 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004173
4174 IntentFilter userFilter = new IntentFilter();
4175 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4176 mContext.registerReceiver(new BroadcastReceiver() {
4177 @Override
4178 public void onReceive(Context context, Intent intent) {
4179 onUserRemoved(intent);
4180 }
4181 }, userFilter);
4182
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004183 synchronized (this) {
4184 // Ensure that any processes we had put on hold are now started
4185 // up.
4186 final int NP = mProcessesOnHold.size();
4187 if (NP > 0) {
4188 ArrayList<ProcessRecord> procs =
4189 new ArrayList<ProcessRecord>(mProcessesOnHold);
4190 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004191 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4192 + procs.get(ip));
4193 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004194 }
4195 }
4196
4197 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004198 // Start looking for apps that are abusing wake locks.
4199 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004200 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004201 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004202 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004203 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004204 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004205 broadcastIntentLocked(null, null,
4206 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4207 null, null, 0, null, null,
4208 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004209 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004210 }
4211 }
4212 }
4213
4214 final void ensureBootCompleted() {
4215 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004216 boolean enableScreen;
4217 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004218 booting = mBooting;
4219 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004220 enableScreen = !mBooted;
4221 mBooted = true;
4222 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004223
4224 if (booting) {
4225 finishBooting();
4226 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004227
4228 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004229 enableScreenAfterBoot();
4230 }
4231 }
4232
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004233 public final void activityPaused(IBinder token) {
4234 final long origId = Binder.clearCallingIdentity();
4235 mMainStack.activityPaused(token, false);
4236 Binder.restoreCallingIdentity(origId);
4237 }
4238
4239 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4240 CharSequence description) {
4241 if (localLOGV) Slog.v(
4242 TAG, "Activity stopped: token=" + token);
4243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 // Refuse possible leaked file descriptors
4245 if (icicle != null && icicle.hasFileDescriptors()) {
4246 throw new IllegalArgumentException("File descriptors passed in Bundle");
4247 }
4248
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004249 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250
4251 final long origId = Binder.clearCallingIdentity();
4252
4253 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004254 r = mMainStack.isInStackLocked(token);
4255 if (r != null) {
4256 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 }
4258 }
4259
4260 if (r != null) {
4261 sendPendingThumbnail(r, null, null, null, false);
4262 }
4263
4264 trimApplications();
4265
4266 Binder.restoreCallingIdentity(origId);
4267 }
4268
4269 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004270 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004271 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 }
4273
4274 public String getCallingPackage(IBinder token) {
4275 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004276 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004277 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 }
4279 }
4280
4281 public ComponentName getCallingActivity(IBinder token) {
4282 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004283 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 return r != null ? r.intent.getComponent() : null;
4285 }
4286 }
4287
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004288 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004289 ActivityRecord r = mMainStack.isInStackLocked(token);
4290 if (r == null) {
4291 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004293 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 }
4295
4296 public ComponentName getActivityClassForToken(IBinder token) {
4297 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004298 ActivityRecord r = mMainStack.isInStackLocked(token);
4299 if (r == null) {
4300 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004302 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 }
4304 }
4305
4306 public String getPackageForToken(IBinder token) {
4307 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004308 ActivityRecord r = mMainStack.isInStackLocked(token);
4309 if (r == null) {
4310 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004312 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 }
4314 }
4315
4316 public IIntentSender getIntentSender(int type,
4317 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004318 int requestCode, Intent[] intents, String[] resolvedTypes,
4319 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004320 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004322 if (intents != null) {
4323 if (intents.length < 1) {
4324 throw new IllegalArgumentException("Intents array length must be >= 1");
4325 }
4326 for (int i=0; i<intents.length; i++) {
4327 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004328 if (intent != null) {
4329 if (intent.hasFileDescriptors()) {
4330 throw new IllegalArgumentException("File descriptors passed in Intent");
4331 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004332 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004333 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4334 throw new IllegalArgumentException(
4335 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4336 }
4337 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004338 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004339 }
4340 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004341 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004342 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004343 }
4344 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004345 if (options != null) {
4346 if (options.hasFileDescriptors()) {
4347 throw new IllegalArgumentException("File descriptors passed in options");
4348 }
4349 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 synchronized(this) {
4352 int callingUid = Binder.getCallingUid();
4353 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004354 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004355 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004356 .getPackageUid(packageName, UserId.getUserId(callingUid));
4357 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 String msg = "Permission Denial: getIntentSender() from pid="
4359 + Binder.getCallingPid()
4360 + ", uid=" + Binder.getCallingUid()
4361 + ", (need uid=" + uid + ")"
4362 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004363 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 throw new SecurityException(msg);
4365 }
4366 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004367
Amith Yamasani742a6712011-05-04 14:49:28 -07004368 if (DEBUG_MU)
4369 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4370 + Binder.getOrigCallingUid());
4371 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004372 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 } catch (RemoteException e) {
4375 throw new SecurityException(e);
4376 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004377 }
4378 }
4379
4380 IIntentSender getIntentSenderLocked(int type,
4381 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004382 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4383 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004384 if (DEBUG_MU)
4385 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004386 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004387 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004388 activity = mMainStack.isInStackLocked(token);
4389 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004390 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004392 if (activity.finishing) {
4393 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004395 }
4396
4397 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4398 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4399 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4400 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4401 |PendingIntent.FLAG_UPDATE_CURRENT);
4402
4403 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4404 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004405 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004406 WeakReference<PendingIntentRecord> ref;
4407 ref = mIntentSenderRecords.get(key);
4408 PendingIntentRecord rec = ref != null ? ref.get() : null;
4409 if (rec != null) {
4410 if (!cancelCurrent) {
4411 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004412 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004413 rec.key.requestIntent.replaceExtras(intents != null ?
4414 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004415 }
4416 if (intents != null) {
4417 intents[intents.length-1] = rec.key.requestIntent;
4418 rec.key.allIntents = intents;
4419 rec.key.allResolvedTypes = resolvedTypes;
4420 } else {
4421 rec.key.allIntents = null;
4422 rec.key.allResolvedTypes = null;
4423 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004425 return rec;
4426 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004427 rec.canceled = true;
4428 mIntentSenderRecords.remove(key);
4429 }
4430 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431 return rec;
4432 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004433 rec = new PendingIntentRecord(this, key, callingUid);
4434 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004435 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004436 if (activity.pendingResults == null) {
4437 activity.pendingResults
4438 = new HashSet<WeakReference<PendingIntentRecord>>();
4439 }
4440 activity.pendingResults.add(rec.ref);
4441 }
4442 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 }
4444
4445 public void cancelIntentSender(IIntentSender sender) {
4446 if (!(sender instanceof PendingIntentRecord)) {
4447 return;
4448 }
4449 synchronized(this) {
4450 PendingIntentRecord rec = (PendingIntentRecord)sender;
4451 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004452 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004453 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004454 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 String msg = "Permission Denial: cancelIntentSender() from pid="
4456 + Binder.getCallingPid()
4457 + ", uid=" + Binder.getCallingUid()
4458 + " is not allowed to cancel packges "
4459 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004460 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 throw new SecurityException(msg);
4462 }
4463 } catch (RemoteException e) {
4464 throw new SecurityException(e);
4465 }
4466 cancelIntentSenderLocked(rec, true);
4467 }
4468 }
4469
4470 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4471 rec.canceled = true;
4472 mIntentSenderRecords.remove(rec.key);
4473 if (cleanActivity && rec.key.activity != null) {
4474 rec.key.activity.pendingResults.remove(rec.ref);
4475 }
4476 }
4477
4478 public String getPackageForIntentSender(IIntentSender pendingResult) {
4479 if (!(pendingResult instanceof PendingIntentRecord)) {
4480 return null;
4481 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004482 try {
4483 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4484 return res.key.packageName;
4485 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 }
4487 return null;
4488 }
4489
Christopher Tatec4a07d12012-04-06 14:19:13 -07004490 public int getUidForIntentSender(IIntentSender sender) {
4491 if (sender instanceof PendingIntentRecord) {
4492 try {
4493 PendingIntentRecord res = (PendingIntentRecord)sender;
4494 return res.uid;
4495 } catch (ClassCastException e) {
4496 }
4497 }
4498 return -1;
4499 }
4500
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004501 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4502 if (!(pendingResult instanceof PendingIntentRecord)) {
4503 return false;
4504 }
4505 try {
4506 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4507 if (res.key.allIntents == null) {
4508 return false;
4509 }
4510 for (int i=0; i<res.key.allIntents.length; i++) {
4511 Intent intent = res.key.allIntents[i];
4512 if (intent.getPackage() != null && intent.getComponent() != null) {
4513 return false;
4514 }
4515 }
4516 return true;
4517 } catch (ClassCastException e) {
4518 }
4519 return false;
4520 }
4521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004522 public void setProcessLimit(int max) {
4523 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4524 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004525 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004526 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004527 mProcessLimitOverride = max;
4528 }
4529 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 }
4531
4532 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004533 synchronized (this) {
4534 return mProcessLimitOverride;
4535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 }
4537
4538 void foregroundTokenDied(ForegroundToken token) {
4539 synchronized (ActivityManagerService.this) {
4540 synchronized (mPidsSelfLocked) {
4541 ForegroundToken cur
4542 = mForegroundProcesses.get(token.pid);
4543 if (cur != token) {
4544 return;
4545 }
4546 mForegroundProcesses.remove(token.pid);
4547 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4548 if (pr == null) {
4549 return;
4550 }
4551 pr.forcingToForeground = null;
4552 pr.foregroundServices = false;
4553 }
4554 updateOomAdjLocked();
4555 }
4556 }
4557
4558 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4559 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4560 "setProcessForeground()");
4561 synchronized(this) {
4562 boolean changed = false;
4563
4564 synchronized (mPidsSelfLocked) {
4565 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004566 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004567 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 return;
4569 }
4570 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4571 if (oldToken != null) {
4572 oldToken.token.unlinkToDeath(oldToken, 0);
4573 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004574 if (pr != null) {
4575 pr.forcingToForeground = null;
4576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 changed = true;
4578 }
4579 if (isForeground && token != null) {
4580 ForegroundToken newToken = new ForegroundToken() {
4581 public void binderDied() {
4582 foregroundTokenDied(this);
4583 }
4584 };
4585 newToken.pid = pid;
4586 newToken.token = token;
4587 try {
4588 token.linkToDeath(newToken, 0);
4589 mForegroundProcesses.put(pid, newToken);
4590 pr.forcingToForeground = token;
4591 changed = true;
4592 } catch (RemoteException e) {
4593 // If the process died while doing this, we will later
4594 // do the cleanup with the process death link.
4595 }
4596 }
4597 }
4598
4599 if (changed) {
4600 updateOomAdjLocked();
4601 }
4602 }
4603 }
4604
4605 // =========================================================
4606 // PERMISSIONS
4607 // =========================================================
4608
4609 static class PermissionController extends IPermissionController.Stub {
4610 ActivityManagerService mActivityManagerService;
4611 PermissionController(ActivityManagerService activityManagerService) {
4612 mActivityManagerService = activityManagerService;
4613 }
4614
4615 public boolean checkPermission(String permission, int pid, int uid) {
4616 return mActivityManagerService.checkPermission(permission, pid,
4617 uid) == PackageManager.PERMISSION_GRANTED;
4618 }
4619 }
4620
4621 /**
4622 * This can be called with or without the global lock held.
4623 */
4624 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004625 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 // We might be performing an operation on behalf of an indirect binder
4627 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4628 // client identity accordingly before proceeding.
4629 Identity tlsIdentity = sCallerIdentity.get();
4630 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004631 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4633 uid = tlsIdentity.uid;
4634 pid = tlsIdentity.pid;
4635 }
4636
4637 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004638 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 return PackageManager.PERMISSION_GRANTED;
4640 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004641 // Isolated processes don't get any permissions.
4642 if (UserId.isIsolated(uid)) {
4643 return PackageManager.PERMISSION_DENIED;
4644 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004645 // If there is a uid that owns whatever is being accessed, it has
4646 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004647 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004648 return PackageManager.PERMISSION_GRANTED;
4649 }
4650 // If the target is not exported, then nobody else can get to it.
4651 if (!exported) {
4652 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004653 return PackageManager.PERMISSION_DENIED;
4654 }
4655 if (permission == null) {
4656 return PackageManager.PERMISSION_GRANTED;
4657 }
4658 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004659 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 .checkUidPermission(permission, uid);
4661 } catch (RemoteException e) {
4662 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004663 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 }
4665 return PackageManager.PERMISSION_DENIED;
4666 }
4667
4668 /**
4669 * As the only public entry point for permissions checking, this method
4670 * can enforce the semantic that requesting a check on a null global
4671 * permission is automatically denied. (Internally a null permission
4672 * string is used when calling {@link #checkComponentPermission} in cases
4673 * when only uid-based security is needed.)
4674 *
4675 * This can be called with or without the global lock held.
4676 */
4677 public int checkPermission(String permission, int pid, int uid) {
4678 if (permission == null) {
4679 return PackageManager.PERMISSION_DENIED;
4680 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004681 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
4683
4684 /**
4685 * Binder IPC calls go through the public entry point.
4686 * This can be called with or without the global lock held.
4687 */
4688 int checkCallingPermission(String permission) {
4689 return checkPermission(permission,
4690 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004691 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 }
4693
4694 /**
4695 * This can be called with or without the global lock held.
4696 */
4697 void enforceCallingPermission(String permission, String func) {
4698 if (checkCallingPermission(permission)
4699 == PackageManager.PERMISSION_GRANTED) {
4700 return;
4701 }
4702
4703 String msg = "Permission Denial: " + func + " from pid="
4704 + Binder.getCallingPid()
4705 + ", uid=" + Binder.getCallingUid()
4706 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004707 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 throw new SecurityException(msg);
4709 }
4710
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004711 /**
4712 * Determine if UID is holding permissions required to access {@link Uri} in
4713 * the given {@link ProviderInfo}. Final permission checking is always done
4714 * in {@link ContentProvider}.
4715 */
4716 private final boolean checkHoldingPermissionsLocked(
4717 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004718 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4719 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004720
4721 if (pi.applicationInfo.uid == uid) {
4722 return true;
4723 } else if (!pi.exported) {
4724 return false;
4725 }
4726
4727 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4728 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004730 // check if target holds top-level <provider> permissions
4731 if (!readMet && pi.readPermission != null
4732 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4733 readMet = true;
4734 }
4735 if (!writeMet && pi.writePermission != null
4736 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4737 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004738 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004739
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004740 // track if unprotected read/write is allowed; any denied
4741 // <path-permission> below removes this ability
4742 boolean allowDefaultRead = pi.readPermission == null;
4743 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004744
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004745 // check if target holds any <path-permission> that match uri
4746 final PathPermission[] pps = pi.pathPermissions;
4747 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004748 final String path = uri.getPath();
4749 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004750 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004751 i--;
4752 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004753 if (pp.match(path)) {
4754 if (!readMet) {
4755 final String pprperm = pp.getReadPermission();
4756 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4757 + pprperm + " for " + pp.getPath()
4758 + ": match=" + pp.match(path)
4759 + " check=" + pm.checkUidPermission(pprperm, uid));
4760 if (pprperm != null) {
4761 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4762 readMet = true;
4763 } else {
4764 allowDefaultRead = false;
4765 }
4766 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004767 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004768 if (!writeMet) {
4769 final String ppwperm = pp.getWritePermission();
4770 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4771 + ppwperm + " for " + pp.getPath()
4772 + ": match=" + pp.match(path)
4773 + " check=" + pm.checkUidPermission(ppwperm, uid));
4774 if (ppwperm != null) {
4775 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4776 writeMet = true;
4777 } else {
4778 allowDefaultWrite = false;
4779 }
4780 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004781 }
4782 }
4783 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004784 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004785
4786 // grant unprotected <provider> read/write, if not blocked by
4787 // <path-permission> above
4788 if (allowDefaultRead) readMet = true;
4789 if (allowDefaultWrite) writeMet = true;
4790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791 } catch (RemoteException e) {
4792 return false;
4793 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004794
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004795 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 }
4797
4798 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4799 int modeFlags) {
4800 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004801 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 return true;
4803 }
4804 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4805 if (perms == null) return false;
4806 UriPermission perm = perms.get(uri);
4807 if (perm == null) return false;
4808 return (modeFlags&perm.modeFlags) == modeFlags;
4809 }
4810
4811 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004812 enforceNotIsolatedCaller("checkUriPermission");
4813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 // Another redirected-binder-call permissions check as in
4815 // {@link checkComponentPermission}.
4816 Identity tlsIdentity = sCallerIdentity.get();
4817 if (tlsIdentity != null) {
4818 uid = tlsIdentity.uid;
4819 pid = tlsIdentity.pid;
4820 }
4821
Amith Yamasani742a6712011-05-04 14:49:28 -07004822 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 // Our own process gets to do everything.
4824 if (pid == MY_PID) {
4825 return PackageManager.PERMISSION_GRANTED;
4826 }
4827 synchronized(this) {
4828 return checkUriPermissionLocked(uri, uid, modeFlags)
4829 ? PackageManager.PERMISSION_GRANTED
4830 : PackageManager.PERMISSION_DENIED;
4831 }
4832 }
4833
Dianne Hackborn39792d22010-08-19 18:01:52 -07004834 /**
4835 * Check if the targetPkg can be granted permission to access uri by
4836 * the callingUid using the given modeFlags. Throws a security exception
4837 * if callingUid is not allowed to do this. Returns the uid of the target
4838 * if the URI permission grant should be performed; returns -1 if it is not
4839 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004840 * If you already know the uid of the target, you can supply it in
4841 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004842 */
4843 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004844 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4846 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4847 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004848 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004849 }
4850
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004851 if (targetPkg != null) {
4852 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4853 "Checking grant " + targetPkg + " permission to " + uri);
4854 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004855
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004856 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857
4858 // If this is not a content: uri, we can't do anything with it.
4859 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004860 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004861 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004862 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 }
4864
4865 String name = uri.getAuthority();
4866 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004867 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4868 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 if (cpr != null) {
4870 pi = cpr.info;
4871 } else {
4872 try {
4873 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004874 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004875 } catch (RemoteException ex) {
4876 }
4877 }
4878 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004879 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004880 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004881 }
4882
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004883 int targetUid = lastTargetUid;
4884 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004885 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004886 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004887 if (targetUid < 0) {
4888 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4889 "Can't grant URI permission no uid for: " + targetPkg);
4890 return -1;
4891 }
4892 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004893 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 }
4896
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004897 if (targetUid >= 0) {
4898 // First... does the target actually need this permission?
4899 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4900 // No need to grant the target this permission.
4901 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4902 "Target " + targetPkg + " already has full permission to " + uri);
4903 return -1;
4904 }
4905 } else {
4906 // First... there is no target package, so can anyone access it?
4907 boolean allowed = pi.exported;
4908 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4909 if (pi.readPermission != null) {
4910 allowed = false;
4911 }
4912 }
4913 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4914 if (pi.writePermission != null) {
4915 allowed = false;
4916 }
4917 }
4918 if (allowed) {
4919 return -1;
4920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 }
4922
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004923 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 if (!pi.grantUriPermissions) {
4925 throw new SecurityException("Provider " + pi.packageName
4926 + "/" + pi.name
4927 + " does not allow granting of Uri permissions (uri "
4928 + uri + ")");
4929 }
4930 if (pi.uriPermissionPatterns != null) {
4931 final int N = pi.uriPermissionPatterns.length;
4932 boolean allowed = false;
4933 for (int i=0; i<N; i++) {
4934 if (pi.uriPermissionPatterns[i] != null
4935 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4936 allowed = true;
4937 break;
4938 }
4939 }
4940 if (!allowed) {
4941 throw new SecurityException("Provider " + pi.packageName
4942 + "/" + pi.name
4943 + " does not allow granting of permission to path of Uri "
4944 + uri);
4945 }
4946 }
4947
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004948 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004950 if (callingUid != Process.myUid()) {
4951 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4952 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4953 throw new SecurityException("Uid " + callingUid
4954 + " does not have permission to uri " + uri);
4955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 }
4957 }
4958
Dianne Hackborn39792d22010-08-19 18:01:52 -07004959 return targetUid;
4960 }
4961
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004962 public int checkGrantUriPermission(int callingUid, String targetPkg,
4963 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004964 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004965 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004966 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004967 }
4968 }
4969
Dianne Hackborn39792d22010-08-19 18:01:52 -07004970 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4971 Uri uri, int modeFlags, UriPermissionOwner owner) {
4972 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4973 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4974 if (modeFlags == 0) {
4975 return;
4976 }
4977
4978 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 // to the uri, and the target doesn't. Let's now give this to
4980 // the target.
4981
Joe Onorato8a9b2202010-02-26 18:56:32 -08004982 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004983 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 HashMap<Uri, UriPermission> targetUris
4986 = mGrantedUriPermissions.get(targetUid);
4987 if (targetUris == null) {
4988 targetUris = new HashMap<Uri, UriPermission>();
4989 mGrantedUriPermissions.put(targetUid, targetUris);
4990 }
4991
4992 UriPermission perm = targetUris.get(uri);
4993 if (perm == null) {
4994 perm = new UriPermission(targetUid, uri);
4995 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004996 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004999 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005001 } else {
5002 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5003 perm.readOwners.add(owner);
5004 owner.addReadPermission(perm);
5005 }
5006 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5007 perm.writeOwners.add(owner);
5008 owner.addWritePermission(perm);
5009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005010 }
5011 }
5012
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005013 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5014 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005015 if (targetPkg == null) {
5016 throw new NullPointerException("targetPkg");
5017 }
5018
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005019 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005020 if (targetUid < 0) {
5021 return;
5022 }
5023
5024 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5025 }
5026
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005027 static class NeededUriGrants extends ArrayList<Uri> {
5028 final String targetPkg;
5029 final int targetUid;
5030 final int flags;
5031
5032 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5033 targetPkg = _targetPkg;
5034 targetUid = _targetUid;
5035 flags = _flags;
5036 }
5037 }
5038
Dianne Hackborn39792d22010-08-19 18:01:52 -07005039 /**
5040 * Like checkGrantUriPermissionLocked, but takes an Intent.
5041 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005042 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5043 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005044 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005045 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5046 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005047 + " from " + intent + "; flags=0x"
5048 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5049
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005050 if (targetPkg == null) {
5051 throw new NullPointerException("targetPkg");
5052 }
5053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005055 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 }
5057 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005058 ClipData clip = intent.getClipData();
5059 if (data == null && clip == null) {
5060 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005061 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005062 if (data != null) {
5063 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5064 mode, needed != null ? needed.targetUid : -1);
5065 if (target > 0) {
5066 if (needed == null) {
5067 needed = new NeededUriGrants(targetPkg, target, mode);
5068 }
5069 needed.add(data);
5070 }
5071 }
5072 if (clip != null) {
5073 for (int i=0; i<clip.getItemCount(); i++) {
5074 Uri uri = clip.getItemAt(i).getUri();
5075 if (uri != null) {
5076 int target = -1;
5077 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5078 mode, needed != null ? needed.targetUid : -1);
5079 if (target > 0) {
5080 if (needed == null) {
5081 needed = new NeededUriGrants(targetPkg, target, mode);
5082 }
5083 needed.add(uri);
5084 }
5085 } else {
5086 Intent clipIntent = clip.getItemAt(i).getIntent();
5087 if (clipIntent != null) {
5088 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5089 callingUid, targetPkg, clipIntent, mode, needed);
5090 if (newNeeded != null) {
5091 needed = newNeeded;
5092 }
5093 }
5094 }
5095 }
5096 }
5097
5098 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005099 }
5100
5101 /**
5102 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5103 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005104 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5105 UriPermissionOwner owner) {
5106 if (needed != null) {
5107 for (int i=0; i<needed.size(); i++) {
5108 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5109 needed.get(i), needed.flags, owner);
5110 }
5111 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005112 }
5113
5114 void grantUriPermissionFromIntentLocked(int callingUid,
5115 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005116 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005117 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005118 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 return;
5120 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005121
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005122 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 }
5124
5125 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5126 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005127 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 synchronized(this) {
5129 final ProcessRecord r = getRecordForAppLocked(caller);
5130 if (r == null) {
5131 throw new SecurityException("Unable to find app for caller "
5132 + caller
5133 + " when granting permission to uri " + uri);
5134 }
5135 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005136 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 }
5138 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005139 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 }
5141
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005142 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 null);
5144 }
5145 }
5146
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005147 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5149 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5150 HashMap<Uri, UriPermission> perms
5151 = mGrantedUriPermissions.get(perm.uid);
5152 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005153 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005154 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 perms.remove(perm.uri);
5156 if (perms.size() == 0) {
5157 mGrantedUriPermissions.remove(perm.uid);
5158 }
5159 }
5160 }
5161 }
5162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5164 int modeFlags) {
5165 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5166 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5167 if (modeFlags == 0) {
5168 return;
5169 }
5170
Joe Onorato8a9b2202010-02-26 18:56:32 -08005171 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005172 "Revoking all granted permissions to " + uri);
5173
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005174 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175
5176 final String authority = uri.getAuthority();
5177 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005178 int userId = UserId.getUserId(callingUid);
5179 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180 if (cpr != null) {
5181 pi = cpr.info;
5182 } else {
5183 try {
5184 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005185 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 } catch (RemoteException ex) {
5187 }
5188 }
5189 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005190 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 return;
5192 }
5193
5194 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005195 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 // Right now, if you are not the original owner of the permission,
5197 // you are not allowed to revoke it.
5198 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5199 throw new SecurityException("Uid " + callingUid
5200 + " does not have permission to uri " + uri);
5201 //}
5202 }
5203
5204 // Go through all of the permissions and remove any that match.
5205 final List<String> SEGMENTS = uri.getPathSegments();
5206 if (SEGMENTS != null) {
5207 final int NS = SEGMENTS.size();
5208 int N = mGrantedUriPermissions.size();
5209 for (int i=0; i<N; i++) {
5210 HashMap<Uri, UriPermission> perms
5211 = mGrantedUriPermissions.valueAt(i);
5212 Iterator<UriPermission> it = perms.values().iterator();
5213 toploop:
5214 while (it.hasNext()) {
5215 UriPermission perm = it.next();
5216 Uri targetUri = perm.uri;
5217 if (!authority.equals(targetUri.getAuthority())) {
5218 continue;
5219 }
5220 List<String> targetSegments = targetUri.getPathSegments();
5221 if (targetSegments == null) {
5222 continue;
5223 }
5224 if (targetSegments.size() < NS) {
5225 continue;
5226 }
5227 for (int j=0; j<NS; j++) {
5228 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5229 continue toploop;
5230 }
5231 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005232 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005233 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 perm.clearModes(modeFlags);
5235 if (perm.modeFlags == 0) {
5236 it.remove();
5237 }
5238 }
5239 if (perms.size() == 0) {
5240 mGrantedUriPermissions.remove(
5241 mGrantedUriPermissions.keyAt(i));
5242 N--;
5243 i--;
5244 }
5245 }
5246 }
5247 }
5248
5249 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5250 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005251 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252 synchronized(this) {
5253 final ProcessRecord r = getRecordForAppLocked(caller);
5254 if (r == null) {
5255 throw new SecurityException("Unable to find app for caller "
5256 + caller
5257 + " when revoking permission to uri " + uri);
5258 }
5259 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005260 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 return;
5262 }
5263
5264 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5265 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5266 if (modeFlags == 0) {
5267 return;
5268 }
5269
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005270 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271
5272 final String authority = uri.getAuthority();
5273 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005274 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005275 if (cpr != null) {
5276 pi = cpr.info;
5277 } else {
5278 try {
5279 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005280 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 } catch (RemoteException ex) {
5282 }
5283 }
5284 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005285 Slog.w(TAG, "No content provider found for permission revoke: "
5286 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 return;
5288 }
5289
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005290 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 }
5292 }
5293
Dianne Hackborn7e269642010-08-25 19:50:20 -07005294 @Override
5295 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005296 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005297 synchronized(this) {
5298 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5299 return owner.getExternalTokenLocked();
5300 }
5301 }
5302
5303 @Override
5304 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5305 Uri uri, int modeFlags) {
5306 synchronized(this) {
5307 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5308 if (owner == null) {
5309 throw new IllegalArgumentException("Unknown owner: " + token);
5310 }
5311 if (fromUid != Binder.getCallingUid()) {
5312 if (Binder.getCallingUid() != Process.myUid()) {
5313 // Only system code can grant URI permissions on behalf
5314 // of other users.
5315 throw new SecurityException("nice try");
5316 }
5317 }
5318 if (targetPkg == null) {
5319 throw new IllegalArgumentException("null target");
5320 }
5321 if (uri == null) {
5322 throw new IllegalArgumentException("null uri");
5323 }
5324
5325 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5326 }
5327 }
5328
5329 @Override
5330 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5331 synchronized(this) {
5332 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5333 if (owner == null) {
5334 throw new IllegalArgumentException("Unknown owner: " + token);
5335 }
5336
5337 if (uri == null) {
5338 owner.removeUriPermissionsLocked(mode);
5339 } else {
5340 owner.removeUriPermissionLocked(uri, mode);
5341 }
5342 }
5343 }
5344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5346 synchronized (this) {
5347 ProcessRecord app =
5348 who != null ? getRecordForAppLocked(who) : null;
5349 if (app == null) return;
5350
5351 Message msg = Message.obtain();
5352 msg.what = WAIT_FOR_DEBUGGER_MSG;
5353 msg.obj = app;
5354 msg.arg1 = waiting ? 1 : 0;
5355 mHandler.sendMessage(msg);
5356 }
5357 }
5358
5359 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005360 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5361 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005363 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005364 outInfo.threshold = homeAppMem;
5365 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5366 outInfo.hiddenAppThreshold = hiddenAppMem;
5367 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005368 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005369 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5370 ProcessList.VISIBLE_APP_ADJ);
5371 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5372 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005373 }
5374
5375 // =========================================================
5376 // TASK MANAGEMENT
5377 // =========================================================
5378
5379 public List getTasks(int maxNum, int flags,
5380 IThumbnailReceiver receiver) {
5381 ArrayList list = new ArrayList();
5382
5383 PendingThumbnailsRecord pending = null;
5384 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005385 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386
5387 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005388 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5390 + ", receiver=" + receiver);
5391
5392 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5393 != PackageManager.PERMISSION_GRANTED) {
5394 if (receiver != null) {
5395 // If the caller wants to wait for pending thumbnails,
5396 // it ain't gonna get them.
5397 try {
5398 receiver.finished();
5399 } catch (RemoteException ex) {
5400 }
5401 }
5402 String msg = "Permission Denial: getTasks() from pid="
5403 + Binder.getCallingPid()
5404 + ", uid=" + Binder.getCallingUid()
5405 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005406 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005407 throw new SecurityException(msg);
5408 }
5409
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005410 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005411 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005412 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005413 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 TaskRecord curTask = null;
5415 int numActivities = 0;
5416 int numRunning = 0;
5417 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005418 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005420 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421
5422 // Initialize state for next task if needed.
5423 if (top == null ||
5424 (top.state == ActivityState.INITIALIZING
5425 && top.task == r.task)) {
5426 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 curTask = r.task;
5428 numActivities = numRunning = 0;
5429 }
5430
5431 // Add 'r' into the current task.
5432 numActivities++;
5433 if (r.app != null && r.app.thread != null) {
5434 numRunning++;
5435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436
Joe Onorato8a9b2202010-02-26 18:56:32 -08005437 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 TAG, r.intent.getComponent().flattenToShortString()
5439 + ": task=" + r.task);
5440
5441 // If the next one is a different task, generate a new
5442 // TaskInfo entry for what we have.
5443 if (next == null || next.task != curTask) {
5444 ActivityManager.RunningTaskInfo ci
5445 = new ActivityManager.RunningTaskInfo();
5446 ci.id = curTask.taskId;
5447 ci.baseActivity = r.intent.getComponent();
5448 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005449 if (top.thumbHolder != null) {
5450 ci.description = top.thumbHolder.lastDescription;
5451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 ci.numActivities = numActivities;
5453 ci.numRunning = numRunning;
5454 //System.out.println(
5455 // "#" + maxNum + ": " + " descr=" + ci.description);
5456 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005457 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 TAG, "State=" + top.state + "Idle=" + top.idle
5459 + " app=" + top.app
5460 + " thr=" + (top.app != null ? top.app.thread : null));
5461 if (top.state == ActivityState.RESUMED
5462 || top.state == ActivityState.PAUSING) {
5463 if (top.idle && top.app != null
5464 && top.app.thread != null) {
5465 topRecord = top;
5466 topThumbnail = top.app.thread;
5467 } else {
5468 top.thumbnailNeeded = true;
5469 }
5470 }
5471 if (pending == null) {
5472 pending = new PendingThumbnailsRecord(receiver);
5473 }
5474 pending.pendingRecords.add(top);
5475 }
5476 list.add(ci);
5477 maxNum--;
5478 top = null;
5479 }
5480 }
5481
5482 if (pending != null) {
5483 mPendingThumbnails.add(pending);
5484 }
5485 }
5486
Joe Onorato8a9b2202010-02-26 18:56:32 -08005487 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488
5489 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005490 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005491 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005492 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005494 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005495 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 }
5497 }
5498
5499 if (pending == null && receiver != null) {
5500 // In this case all thumbnails were available and the client
5501 // is being asked to be told when the remaining ones come in...
5502 // which is unusually, since the top-most currently running
5503 // activity should never have a canned thumbnail! Oh well.
5504 try {
5505 receiver.finished();
5506 } catch (RemoteException ex) {
5507 }
5508 }
5509
5510 return list;
5511 }
5512
5513 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5514 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005515 final int callingUid = Binder.getCallingUid();
5516 // If it's the system uid asking, then use the current user id.
5517 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5518 // require the entire list.
5519 final int callingUserId = callingUid == Process.SYSTEM_UID
5520 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 synchronized (this) {
5522 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5523 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005524 final boolean detailed = checkCallingPermission(
5525 android.Manifest.permission.GET_DETAILED_TASKS)
5526 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005528 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 final int N = mRecentTasks.size();
5531 ArrayList<ActivityManager.RecentTaskInfo> res
5532 = new ArrayList<ActivityManager.RecentTaskInfo>(
5533 maxNum < N ? maxNum : N);
5534 for (int i=0; i<N && maxNum > 0; i++) {
5535 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005536 // Only add calling user's recent tasks
5537 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005538 // Return the entry if desired by the caller. We always return
5539 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005540 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005541 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5542 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005543
Dianne Hackborn905577f2011-09-07 18:31:28 -07005544 if (i == 0
5545 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 || (tr.intent == null)
5547 || ((tr.intent.getFlags()
5548 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5549 ActivityManager.RecentTaskInfo rti
5550 = new ActivityManager.RecentTaskInfo();
5551 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005552 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 rti.baseIntent = new Intent(
5554 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005555 if (!detailed) {
5556 rti.baseIntent.replaceExtras((Bundle)null);
5557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005559 rti.description = tr.lastDescription;
5560
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005561 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5562 // Check whether this activity is currently available.
5563 try {
5564 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005565 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5566 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005567 continue;
5568 }
5569 } else if (rti.baseIntent != null) {
5570 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005571 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005572 continue;
5573 }
5574 }
5575 } catch (RemoteException e) {
5576 // Will never happen.
5577 }
5578 }
5579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 res.add(rti);
5581 maxNum--;
5582 }
5583 }
5584 return res;
5585 }
5586 }
5587
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005588 private TaskRecord taskForIdLocked(int id) {
5589 final int N = mRecentTasks.size();
5590 for (int i=0; i<N; i++) {
5591 TaskRecord tr = mRecentTasks.get(i);
5592 if (tr.taskId == id) {
5593 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005594 }
5595 }
5596 return null;
5597 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005598
5599 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5600 synchronized (this) {
5601 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5602 "getTaskThumbnails()");
5603 TaskRecord tr = taskForIdLocked(id);
5604 if (tr != null) {
5605 return mMainStack.getTaskThumbnailsLocked(tr);
5606 }
5607 }
5608 return null;
5609 }
5610
5611 public boolean removeSubTask(int taskId, int subTaskIndex) {
5612 synchronized (this) {
5613 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5614 "removeSubTask()");
5615 long ident = Binder.clearCallingIdentity();
5616 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005617 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5618 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005619 } finally {
5620 Binder.restoreCallingIdentity(ident);
5621 }
5622 }
5623 }
5624
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005625 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5626 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005627 Intent baseIntent = new Intent(
5628 tr.intent != null ? tr.intent : tr.affinityIntent);
5629 ComponentName component = baseIntent.getComponent();
5630 if (component == null) {
5631 Slog.w(TAG, "Now component for base intent of task: " + tr);
5632 return;
5633 }
5634
5635 // Find any running services associated with this app.
5636 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005637 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005638 if (sr.packageName.equals(component.getPackageName())) {
5639 services.add(sr);
5640 }
5641 }
5642
5643 // Take care of any running services associated with the app.
5644 for (int i=0; i<services.size(); i++) {
5645 ServiceRecord sr = services.get(i);
5646 if (sr.startRequested) {
5647 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005648 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005649 stopServiceLocked(sr);
5650 } else {
5651 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005652 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005653 if (sr.app != null && sr.app.thread != null) {
5654 sendServiceArgsLocked(sr, false);
5655 }
5656 }
5657 }
5658 }
5659
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005660 if (killProcesses) {
5661 // Find any running processes associated with this app.
5662 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5663 SparseArray<ProcessRecord> appProcs
5664 = mProcessNames.getMap().get(component.getPackageName());
5665 if (appProcs != null) {
5666 for (int i=0; i<appProcs.size(); i++) {
5667 procs.add(appProcs.valueAt(i));
5668 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005669 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005670
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005671 // Kill the running processes.
5672 for (int i=0; i<procs.size(); i++) {
5673 ProcessRecord pr = procs.get(i);
5674 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5675 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5676 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5677 pr.processName, pr.setAdj, "remove task");
5678 Process.killProcessQuiet(pr.pid);
5679 } else {
5680 pr.waitingToKill = "remove task";
5681 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005682 }
5683 }
5684 }
5685
5686 public boolean removeTask(int taskId, int flags) {
5687 synchronized (this) {
5688 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5689 "removeTask()");
5690 long ident = Binder.clearCallingIdentity();
5691 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005692 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5693 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005694 if (r != null) {
5695 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005696 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005697 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005698 } else {
5699 TaskRecord tr = null;
5700 int i=0;
5701 while (i < mRecentTasks.size()) {
5702 TaskRecord t = mRecentTasks.get(i);
5703 if (t.taskId == taskId) {
5704 tr = t;
5705 break;
5706 }
5707 i++;
5708 }
5709 if (tr != null) {
5710 if (tr.numActivities <= 0) {
5711 // Caller is just removing a recent task that is
5712 // not actively running. That is easy!
5713 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005714 cleanUpRemovedTaskLocked(tr, flags);
5715 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005716 } else {
5717 Slog.w(TAG, "removeTask: task " + taskId
5718 + " does not have activities to remove, "
5719 + " but numActivities=" + tr.numActivities
5720 + ": " + tr);
5721 }
5722 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005723 }
5724 } finally {
5725 Binder.restoreCallingIdentity(ident);
5726 }
5727 }
5728 return false;
5729 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5732 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005733 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 TaskRecord jt = startTask;
5735
5736 // First look backwards
5737 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005738 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 if (r.task != jt) {
5740 jt = r.task;
5741 if (affinity.equals(jt.affinity)) {
5742 return j;
5743 }
5744 }
5745 }
5746
5747 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005748 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 jt = startTask;
5750 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005751 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 if (r.task != jt) {
5753 if (affinity.equals(jt.affinity)) {
5754 return j;
5755 }
5756 jt = r.task;
5757 }
5758 }
5759
5760 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005761 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 return N-1;
5763 }
5764
5765 return -1;
5766 }
5767
5768 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005769 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005771 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5773 "moveTaskToFront()");
5774
5775 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005776 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5777 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005778 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005779 return;
5780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 final long origId = Binder.clearCallingIdentity();
5782 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005783 TaskRecord tr = taskForIdLocked(task);
5784 if (tr != null) {
5785 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5786 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005788 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5789 // Caller wants the home activity moved with it. To accomplish this,
5790 // we'll just move the home task to the top first.
5791 mMainStack.moveHomeToFrontLocked();
5792 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005793 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005794 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005796 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5797 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005799 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5800 mMainStack.mUserLeaving = true;
5801 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005802 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5803 // Caller wants the home activity moved with it. To accomplish this,
5804 // we'll just move the home task to the top first.
5805 mMainStack.moveHomeToFrontLocked();
5806 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005807 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 return;
5809 }
5810 }
5811 } finally {
5812 Binder.restoreCallingIdentity(origId);
5813 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005814 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 }
5816 }
5817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 public void moveTaskToBack(int task) {
5819 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5820 "moveTaskToBack()");
5821
5822 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005823 if (mMainStack.mResumedActivity != null
5824 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005825 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5826 Binder.getCallingUid(), "Task to back")) {
5827 return;
5828 }
5829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005831 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 Binder.restoreCallingIdentity(origId);
5833 }
5834 }
5835
5836 /**
5837 * Moves an activity, and all of the other activities within the same task, to the bottom
5838 * of the history stack. The activity's order within the task is unchanged.
5839 *
5840 * @param token A reference to the activity we wish to move
5841 * @param nonRoot If false then this only works if the activity is the root
5842 * of a task; if true it will work for any activity in a task.
5843 * @return Returns true if the move completed, false if not.
5844 */
5845 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005846 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 synchronized(this) {
5848 final long origId = Binder.clearCallingIdentity();
5849 int taskId = getTaskForActivityLocked(token, !nonRoot);
5850 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005851 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 }
5853 Binder.restoreCallingIdentity(origId);
5854 }
5855 return false;
5856 }
5857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 public void moveTaskBackwards(int task) {
5859 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5860 "moveTaskBackwards()");
5861
5862 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005863 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5864 Binder.getCallingUid(), "Task backwards")) {
5865 return;
5866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 final long origId = Binder.clearCallingIdentity();
5868 moveTaskBackwardsLocked(task);
5869 Binder.restoreCallingIdentity(origId);
5870 }
5871 }
5872
5873 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005874 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 }
5876
5877 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5878 synchronized(this) {
5879 return getTaskForActivityLocked(token, onlyRoot);
5880 }
5881 }
5882
5883 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005884 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 TaskRecord lastTask = null;
5886 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005887 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005888 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 if (!onlyRoot || lastTask != r.task) {
5890 return r.task.taskId;
5891 }
5892 return -1;
5893 }
5894 lastTask = r.task;
5895 }
5896
5897 return -1;
5898 }
5899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 // =========================================================
5901 // THUMBNAILS
5902 // =========================================================
5903
5904 public void reportThumbnail(IBinder token,
5905 Bitmap thumbnail, CharSequence description) {
5906 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5907 final long origId = Binder.clearCallingIdentity();
5908 sendPendingThumbnail(null, token, thumbnail, description, true);
5909 Binder.restoreCallingIdentity(origId);
5910 }
5911
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005912 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 Bitmap thumbnail, CharSequence description, boolean always) {
5914 TaskRecord task = null;
5915 ArrayList receivers = null;
5916
5917 //System.out.println("Send pending thumbnail: " + r);
5918
5919 synchronized(this) {
5920 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005921 r = mMainStack.isInStackLocked(token);
5922 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 return;
5924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005926 if (thumbnail == null && r.thumbHolder != null) {
5927 thumbnail = r.thumbHolder.lastThumbnail;
5928 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 }
5930 if (thumbnail == null && !always) {
5931 // If there is no thumbnail, and this entry is not actually
5932 // going away, then abort for now and pick up the next
5933 // thumbnail we get.
5934 return;
5935 }
5936 task = r.task;
5937
5938 int N = mPendingThumbnails.size();
5939 int i=0;
5940 while (i<N) {
5941 PendingThumbnailsRecord pr =
5942 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5943 //System.out.println("Looking in " + pr.pendingRecords);
5944 if (pr.pendingRecords.remove(r)) {
5945 if (receivers == null) {
5946 receivers = new ArrayList();
5947 }
5948 receivers.add(pr);
5949 if (pr.pendingRecords.size() == 0) {
5950 pr.finished = true;
5951 mPendingThumbnails.remove(i);
5952 N--;
5953 continue;
5954 }
5955 }
5956 i++;
5957 }
5958 }
5959
5960 if (receivers != null) {
5961 final int N = receivers.size();
5962 for (int i=0; i<N; i++) {
5963 try {
5964 PendingThumbnailsRecord pr =
5965 (PendingThumbnailsRecord)receivers.get(i);
5966 pr.receiver.newThumbnail(
5967 task != null ? task.taskId : -1, thumbnail, description);
5968 if (pr.finished) {
5969 pr.receiver.finished();
5970 }
5971 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005972 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 }
5974 }
5975 }
5976 }
5977
5978 // =========================================================
5979 // CONTENT PROVIDERS
5980 // =========================================================
5981
Jeff Brown10e89712011-07-08 18:52:57 -07005982 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5983 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005985 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005986 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005987 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 } catch (RemoteException ex) {
5989 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005990 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005991 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5992 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 if (providers != null) {
5994 final int N = providers.size();
5995 for (int i=0; i<N; i++) {
5996 ProviderInfo cpi =
5997 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005998
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005999 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006000 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006002 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006003 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006005 if (DEBUG_MU)
6006 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 app.pubProviders.put(cpi.name, cpr);
6008 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006009 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 }
6011 }
6012 return providers;
6013 }
6014
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006015 /**
6016 * Check if {@link ProcessRecord} has a possible chance at accessing the
6017 * given {@link ProviderInfo}. Final permission checking is always done
6018 * in {@link ContentProvider}.
6019 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006021 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006023 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006025 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006026 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 return null;
6028 }
6029 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006030 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 == PackageManager.PERMISSION_GRANTED) {
6032 return null;
6033 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006034
6035 PathPermission[] pps = cpi.pathPermissions;
6036 if (pps != null) {
6037 int i = pps.length;
6038 while (i > 0) {
6039 i--;
6040 PathPermission pp = pps[i];
6041 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006042 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006043 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006044 return null;
6045 }
6046 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006047 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006048 == PackageManager.PERMISSION_GRANTED) {
6049 return null;
6050 }
6051 }
6052 }
6053
Dianne Hackbornb424b632010-08-18 15:59:05 -07006054 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6055 if (perms != null) {
6056 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6057 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6058 return null;
6059 }
6060 }
6061 }
6062
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006063 String msg;
6064 if (!cpi.exported) {
6065 msg = "Permission Denial: opening provider " + cpi.name
6066 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6067 + ", uid=" + callingUid + ") that is not exported from uid "
6068 + cpi.applicationInfo.uid;
6069 } else {
6070 msg = "Permission Denial: opening provider " + cpi.name
6071 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6072 + ", uid=" + callingUid + ") requires "
6073 + cpi.readPermission + " or " + cpi.writePermission;
6074 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006075 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 return msg;
6077 }
6078
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006079 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6080 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006081 if (r != null) {
6082 Integer cnt = r.conProviders.get(cpr);
6083 if (DEBUG_PROVIDER) Slog.v(TAG,
6084 "Adding provider requested by "
6085 + r.processName + " from process "
6086 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6087 + " cnt=" + (cnt == null ? 1 : cnt));
6088 if (cnt == null) {
6089 cpr.clients.add(r);
6090 r.conProviders.put(cpr, new Integer(1));
6091 return true;
6092 } else {
6093 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6094 }
6095 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006096 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006097 }
6098 return false;
6099 }
6100
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006101 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6102 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006103 if (r != null) {
6104 Integer cnt = r.conProviders.get(cpr);
6105 if (DEBUG_PROVIDER) Slog.v(TAG,
6106 "Removing provider requested by "
6107 + r.processName + " from process "
6108 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6109 + " cnt=" + cnt);
6110 if (cnt == null || cnt.intValue() <= 1) {
6111 cpr.clients.remove(r);
6112 r.conProviders.remove(cpr);
6113 return true;
6114 } else {
6115 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6116 }
6117 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006118 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006119 }
6120 return false;
6121 }
6122
Amith Yamasani742a6712011-05-04 14:49:28 -07006123 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006124 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 ContentProviderRecord cpr;
6126 ProviderInfo cpi = null;
6127
6128 synchronized(this) {
6129 ProcessRecord r = null;
6130 if (caller != null) {
6131 r = getRecordForAppLocked(caller);
6132 if (r == null) {
6133 throw new SecurityException(
6134 "Unable to find app for caller " + caller
6135 + " (pid=" + Binder.getCallingPid()
6136 + ") when getting content provider " + name);
6137 }
6138 }
6139
6140 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006141 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006142 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006143 boolean providerRunning = cpr != null;
6144 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006146 String msg;
6147 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6148 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
6150
6151 if (r != null && cpr.canRunHere(r)) {
6152 // This provider has been published or is in the process
6153 // of being published... but it is also allowed to run
6154 // in the caller's process, so don't make a connection
6155 // and just let the caller instantiate its own instance.
6156 if (cpr.provider != null) {
6157 // don't give caller the provider object, it needs
6158 // to make its own.
6159 cpr = new ContentProviderRecord(cpr);
6160 }
6161 return cpr;
6162 }
6163
6164 final long origId = Binder.clearCallingIdentity();
6165
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006166 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006168 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006169 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006170 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006171 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006172 // make sure to count it as being accessed and thus
6173 // back up on the LRU list. This is good because
6174 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006175 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006176 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006177 }
6178
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006179 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006180 if (false) {
6181 if (cpr.name.flattenToShortString().equals(
6182 "com.android.providers.calendar/.CalendarProvider2")) {
6183 Slog.v(TAG, "****************** KILLING "
6184 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006185 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006186 }
6187 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006188 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006189 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6190 // NOTE: there is still a race here where a signal could be
6191 // pending on the process even though we managed to update its
6192 // adj level. Not sure what to do about this, but at least
6193 // the race is now smaller.
6194 if (!success) {
6195 // Uh oh... it looks like the provider's process
6196 // has been killed on us. We need to wait for a new
6197 // process to be started, and make sure its death
6198 // doesn't kill our process.
6199 Slog.i(TAG,
6200 "Existing provider " + cpr.name.flattenToShortString()
6201 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006202 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006203 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006204 if (!lastRef) {
6205 // This wasn't the last ref our process had on
6206 // the provider... we have now been killed, bail.
6207 return null;
6208 }
6209 providerRunning = false;
6210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 }
6212
6213 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006216 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006218 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006219 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006220 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 } catch (RemoteException ex) {
6222 }
6223 if (cpi == null) {
6224 return null;
6225 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006226 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6227 userId = 0;
6228 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006229 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006230
Dianne Hackbornb424b632010-08-18 15:59:05 -07006231 String msg;
6232 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6233 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 }
6235
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006236 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006237 && !cpi.processName.equals("system")) {
6238 // If this content provider does not run in the system
6239 // process, and the system is not yet ready to run other
6240 // processes, then fail fast instead of hanging.
6241 throw new IllegalArgumentException(
6242 "Attempt to launch content provider before system ready");
6243 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006244
6245 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006246 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 final boolean firstClass = cpr == null;
6248 if (firstClass) {
6249 try {
6250 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006251 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 getApplicationInfo(
6253 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006254 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006256 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 + cpi.name);
6258 return null;
6259 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006260 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006261 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 } catch (RemoteException ex) {
6263 // pm is in same process, this will never happen.
6264 }
6265 }
6266
6267 if (r != null && cpr.canRunHere(r)) {
6268 // If this is a multiprocess provider, then just return its
6269 // info and allow the caller to instantiate it. Only do
6270 // this if the provider is the same user as the caller's
6271 // process, or can run as root (so can be in any process).
6272 return cpr;
6273 }
6274
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006275 if (DEBUG_PROVIDER) {
6276 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006277 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006278 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 }
6280
6281 // This is single process, and our app is now connecting to it.
6282 // See if we are already in the process of launching this
6283 // provider.
6284 final int N = mLaunchingProviders.size();
6285 int i;
6286 for (i=0; i<N; i++) {
6287 if (mLaunchingProviders.get(i) == cpr) {
6288 break;
6289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
6291
6292 // If the provider is not already being launched, then get it
6293 // started.
6294 if (i >= N) {
6295 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006296
6297 try {
6298 // Content provider is now in use, its package can't be stopped.
6299 try {
6300 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006301 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006302 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006303 } catch (IllegalArgumentException e) {
6304 Slog.w(TAG, "Failed trying to unstop package "
6305 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006306 }
6307
6308 ProcessRecord proc = startProcessLocked(cpi.processName,
6309 cpr.appInfo, false, 0, "content provider",
6310 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006311 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006312 if (proc == null) {
6313 Slog.w(TAG, "Unable to launch app "
6314 + cpi.applicationInfo.packageName + "/"
6315 + cpi.applicationInfo.uid + " for provider "
6316 + name + ": process is bad");
6317 return null;
6318 }
6319 cpr.launchingApp = proc;
6320 mLaunchingProviders.add(cpr);
6321 } finally {
6322 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 }
6325
6326 // Make sure the provider is published (the same provider class
6327 // may be published under multiple names).
6328 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006329 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006331
Amith Yamasani742a6712011-05-04 14:49:28 -07006332 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006333 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 }
6335 }
6336
6337 // Wait for the provider to be published...
6338 synchronized (cpr) {
6339 while (cpr.provider == null) {
6340 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006341 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 + cpi.applicationInfo.packageName + "/"
6343 + cpi.applicationInfo.uid + " for provider "
6344 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006345 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 cpi.applicationInfo.packageName,
6347 cpi.applicationInfo.uid, name);
6348 return null;
6349 }
6350 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006351 if (DEBUG_MU) {
6352 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6353 + cpr.launchingApp);
6354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 cpr.wait();
6356 } catch (InterruptedException ex) {
6357 }
6358 }
6359 }
6360 return cpr;
6361 }
6362
6363 public final ContentProviderHolder getContentProvider(
6364 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006365 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 if (caller == null) {
6367 String msg = "null IApplicationThread when getting content provider "
6368 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006369 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 throw new SecurityException(msg);
6371 }
6372
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006373 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 }
6375
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006376 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6377 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6378 "Do not have permission in call getContentProviderExternal()");
6379 return getContentProviderExternalUnchecked(name, token);
6380 }
6381
6382 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6383 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 }
6385
6386 /**
6387 * Drop a content provider from a ProcessRecord's bookkeeping
6388 * @param cpr
6389 */
6390 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006391 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006393 int userId = UserId.getUserId(Binder.getCallingUid());
6394 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006396 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006397 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006398 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 return;
6400 }
6401 final ProcessRecord r = getRecordForAppLocked(caller);
6402 if (r == null) {
6403 throw new SecurityException(
6404 "Unable to find app for caller " + caller +
6405 " when removing content provider " + name);
6406 }
6407 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006408 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006409 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6410 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6411 + r.info.processName + " from process "
6412 + localCpr.appInfo.processName);
6413 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006415 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006416 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 return;
6418 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006419 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006420 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 }
6424 }
6425
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006426 public void removeContentProviderExternal(String name, IBinder token) {
6427 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6428 "Do not have permission in call removeContentProviderExternal()");
6429 removeContentProviderExternalUnchecked(name, token);
6430 }
6431
6432 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006434 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6435 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 if(cpr == null) {
6437 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006438 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 return;
6440 }
6441
6442 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006443 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006444 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6445 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006446 if (localCpr.hasExternalProcessHandles()) {
6447 if (localCpr.removeExternalProcessHandleLocked(token)) {
6448 updateOomAdjLocked();
6449 } else {
6450 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6451 + " with no external reference for token: "
6452 + token + ".");
6453 }
6454 } else {
6455 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6456 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
6459 }
6460
6461 public final void publishContentProviders(IApplicationThread caller,
6462 List<ContentProviderHolder> providers) {
6463 if (providers == null) {
6464 return;
6465 }
6466
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006467 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 synchronized(this) {
6469 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006470 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006471 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 if (r == null) {
6473 throw new SecurityException(
6474 "Unable to find app for caller " + caller
6475 + " (pid=" + Binder.getCallingPid()
6476 + ") when publishing content providers");
6477 }
6478
6479 final long origId = Binder.clearCallingIdentity();
6480
6481 final int N = providers.size();
6482 for (int i=0; i<N; i++) {
6483 ContentProviderHolder src = providers.get(i);
6484 if (src == null || src.info == null || src.provider == null) {
6485 continue;
6486 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006487 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006488 if (DEBUG_MU)
6489 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006491 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006492 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 String names[] = dst.info.authority.split(";");
6494 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006495 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
6497
6498 int NL = mLaunchingProviders.size();
6499 int j;
6500 for (j=0; j<NL; j++) {
6501 if (mLaunchingProviders.get(j) == dst) {
6502 mLaunchingProviders.remove(j);
6503 j--;
6504 NL--;
6505 }
6506 }
6507 synchronized (dst) {
6508 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006509 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 dst.notifyAll();
6511 }
6512 updateOomAdjLocked(r);
6513 }
6514 }
6515
6516 Binder.restoreCallingIdentity(origId);
6517 }
6518 }
6519
6520 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006521 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006522 synchronized (mSelf) {
6523 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6524 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006525 if (providers != null) {
6526 for (int i=providers.size()-1; i>=0; i--) {
6527 ProviderInfo pi = (ProviderInfo)providers.get(i);
6528 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6529 Slog.w(TAG, "Not installing system proc provider " + pi.name
6530 + ": not system .apk");
6531 providers.remove(i);
6532 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006533 }
6534 }
6535 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006536 if (providers != null) {
6537 mSystemThread.installSystemProviders(providers);
6538 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006539
6540 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006541
6542 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 }
6544
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006545 /**
6546 * Allows app to retrieve the MIME type of a URI without having permission
6547 * to access its content provider.
6548 *
6549 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6550 *
6551 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6552 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6553 */
6554 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006555 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006556 final String name = uri.getAuthority();
6557 final long ident = Binder.clearCallingIdentity();
6558 ContentProviderHolder holder = null;
6559
6560 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006561 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006562 if (holder != null) {
6563 return holder.provider.getType(uri);
6564 }
6565 } catch (RemoteException e) {
6566 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6567 return null;
6568 } finally {
6569 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006570 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006571 }
6572 Binder.restoreCallingIdentity(ident);
6573 }
6574
6575 return null;
6576 }
6577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 // =========================================================
6579 // GLOBAL MANAGEMENT
6580 // =========================================================
6581
6582 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006583 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 String proc = customProcess != null ? customProcess : info.processName;
6585 BatteryStatsImpl.Uid.Proc ps = null;
6586 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006587 int uid = info.uid;
6588 if (isolated) {
6589 int userId = UserId.getUserId(uid);
6590 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6591 uid = 0;
6592 while (true) {
6593 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6594 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6595 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6596 }
6597 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6598 mNextIsolatedProcessUid++;
6599 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6600 // No process for this uid, use it.
6601 break;
6602 }
6603 stepsLeft--;
6604 if (stepsLeft <= 0) {
6605 return null;
6606 }
6607 }
6608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 synchronized (stats) {
6610 ps = stats.getProcessStatsLocked(info.uid, proc);
6611 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006612 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 }
6614
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006615 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6616 ProcessRecord app;
6617 if (!isolated) {
6618 app = getProcessRecordLocked(info.processName, info.uid);
6619 } else {
6620 app = null;
6621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622
6623 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006624 app = newProcessRecordLocked(null, info, null, isolated);
6625 mProcessNames.put(info.processName, app.uid, app);
6626 if (isolated) {
6627 mIsolatedProcesses.put(app.uid, app);
6628 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006629 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 }
6631
Dianne Hackborne7f97212011-02-24 14:40:20 -08006632 // This package really, really can not be stopped.
6633 try {
6634 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006635 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006636 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006637 } catch (IllegalArgumentException e) {
6638 Slog.w(TAG, "Failed trying to unstop package "
6639 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006640 }
6641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6643 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6644 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006645 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 }
6647 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6648 mPersistentStartingProcesses.add(app);
6649 startProcessLocked(app, "added application", app.processName);
6650 }
6651
6652 return app;
6653 }
6654
6655 public void unhandledBack() {
6656 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6657 "unhandledBack()");
6658
6659 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006660 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006661 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 TAG, "Performing unhandledBack(): stack size = " + count);
6663 if (count > 1) {
6664 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006665 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6667 Binder.restoreCallingIdentity(origId);
6668 }
6669 }
6670 }
6671
6672 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006673 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006675 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 ParcelFileDescriptor pfd = null;
6677 if (cph != null) {
6678 // We record the binder invoker's uid in thread-local storage before
6679 // going to the content provider to open the file. Later, in the code
6680 // that handles all permissions checks, we look for this uid and use
6681 // that rather than the Activity Manager's own uid. The effect is that
6682 // we do the check against the caller's permissions even though it looks
6683 // to the content provider like the Activity Manager itself is making
6684 // the request.
6685 sCallerIdentity.set(new Identity(
6686 Binder.getCallingPid(), Binder.getCallingUid()));
6687 try {
6688 pfd = cph.provider.openFile(uri, "r");
6689 } catch (FileNotFoundException e) {
6690 // do nothing; pfd will be returned null
6691 } finally {
6692 // Ensure that whatever happens, we clean up the identity state
6693 sCallerIdentity.remove();
6694 }
6695
6696 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006697 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006699 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 }
6701 return pfd;
6702 }
6703
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006704 // Actually is sleeping or shutting down or whatever else in the future
6705 // is an inactive state.
6706 public boolean isSleeping() {
6707 return mSleeping || mShuttingDown;
6708 }
6709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006711 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6712 != PackageManager.PERMISSION_GRANTED) {
6713 throw new SecurityException("Requires permission "
6714 + android.Manifest.permission.DEVICE_POWER);
6715 }
6716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006718 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006719 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006721 if (!mSleeping) {
6722 mSleeping = true;
6723 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006724
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006725 // Initialize the wake times of all processes.
6726 checkExcessivePowerUsageLocked(false);
6727 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6728 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6729 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 }
6732 }
6733
Dianne Hackborn55280a92009-05-07 15:53:46 -07006734 public boolean shutdown(int timeout) {
6735 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6736 != PackageManager.PERMISSION_GRANTED) {
6737 throw new SecurityException("Requires permission "
6738 + android.Manifest.permission.SHUTDOWN);
6739 }
6740
6741 boolean timedout = false;
6742
6743 synchronized(this) {
6744 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006745 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006746
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006747 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006748 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006749 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006750 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006751 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006752 long delay = endTime - System.currentTimeMillis();
6753 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006754 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006755 timedout = true;
6756 break;
6757 }
6758 try {
6759 this.wait();
6760 } catch (InterruptedException e) {
6761 }
6762 }
6763 }
6764 }
6765
6766 mUsageStatsService.shutdown();
6767 mBatteryStatsService.shutdown();
6768
6769 return timedout;
6770 }
6771
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006772 public final void activitySlept(IBinder token) {
6773 if (localLOGV) Slog.v(
6774 TAG, "Activity slept: token=" + token);
6775
6776 ActivityRecord r = null;
6777
6778 final long origId = Binder.clearCallingIdentity();
6779
6780 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006781 r = mMainStack.isInStackLocked(token);
6782 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006783 mMainStack.activitySleptLocked(r);
6784 }
6785 }
6786
6787 Binder.restoreCallingIdentity(origId);
6788 }
6789
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006790 private void comeOutOfSleepIfNeededLocked() {
6791 if (!mWentToSleep && !mLockScreenShown) {
6792 if (mSleeping) {
6793 mSleeping = false;
6794 mMainStack.awakeFromSleepingLocked();
6795 mMainStack.resumeTopActivityLocked(null);
6796 }
6797 }
6798 }
6799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006801 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6802 != PackageManager.PERMISSION_GRANTED) {
6803 throw new SecurityException("Requires permission "
6804 + android.Manifest.permission.DEVICE_POWER);
6805 }
6806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006808 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006809 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006810 comeOutOfSleepIfNeededLocked();
6811 }
6812 }
6813
Jeff Brownc042ee22012-05-08 13:03:42 -07006814 private void updateEventDispatchingLocked() {
6815 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6816 }
6817
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006818 public void setLockScreenShown(boolean shown) {
6819 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6820 != PackageManager.PERMISSION_GRANTED) {
6821 throw new SecurityException("Requires permission "
6822 + android.Manifest.permission.DEVICE_POWER);
6823 }
6824
6825 synchronized(this) {
6826 mLockScreenShown = shown;
6827 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 }
6829 }
6830
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006831 public void stopAppSwitches() {
6832 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6833 != PackageManager.PERMISSION_GRANTED) {
6834 throw new SecurityException("Requires permission "
6835 + android.Manifest.permission.STOP_APP_SWITCHES);
6836 }
6837
6838 synchronized(this) {
6839 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6840 + APP_SWITCH_DELAY_TIME;
6841 mDidAppSwitch = false;
6842 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6843 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6844 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6845 }
6846 }
6847
6848 public void resumeAppSwitches() {
6849 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6850 != PackageManager.PERMISSION_GRANTED) {
6851 throw new SecurityException("Requires permission "
6852 + android.Manifest.permission.STOP_APP_SWITCHES);
6853 }
6854
6855 synchronized(this) {
6856 // Note that we don't execute any pending app switches... we will
6857 // let those wait until either the timeout, or the next start
6858 // activity request.
6859 mAppSwitchesAllowedTime = 0;
6860 }
6861 }
6862
6863 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6864 String name) {
6865 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6866 return true;
6867 }
6868
6869 final int perm = checkComponentPermission(
6870 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006871 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006872 if (perm == PackageManager.PERMISSION_GRANTED) {
6873 return true;
6874 }
6875
Joe Onorato8a9b2202010-02-26 18:56:32 -08006876 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006877 return false;
6878 }
6879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 public void setDebugApp(String packageName, boolean waitForDebugger,
6881 boolean persistent) {
6882 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6883 "setDebugApp()");
6884
6885 // Note that this is not really thread safe if there are multiple
6886 // callers into it at the same time, but that's not a situation we
6887 // care about.
6888 if (persistent) {
6889 final ContentResolver resolver = mContext.getContentResolver();
6890 Settings.System.putString(
6891 resolver, Settings.System.DEBUG_APP,
6892 packageName);
6893 Settings.System.putInt(
6894 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6895 waitForDebugger ? 1 : 0);
6896 }
6897
6898 synchronized (this) {
6899 if (!persistent) {
6900 mOrigDebugApp = mDebugApp;
6901 mOrigWaitForDebugger = mWaitForDebugger;
6902 }
6903 mDebugApp = packageName;
6904 mWaitForDebugger = waitForDebugger;
6905 mDebugTransient = !persistent;
6906 if (packageName != null) {
6907 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006908 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 Binder.restoreCallingIdentity(origId);
6910 }
6911 }
6912 }
6913
Siva Velusamy92a8b222012-03-09 16:24:04 -08006914 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6915 synchronized (this) {
6916 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6917 if (!isDebuggable) {
6918 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6919 throw new SecurityException("Process not debuggable: " + app.packageName);
6920 }
6921 }
6922
6923 mOpenGlTraceApp = processName;
6924 }
6925 }
6926
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006927 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6928 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6929 synchronized (this) {
6930 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6931 if (!isDebuggable) {
6932 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6933 throw new SecurityException("Process not debuggable: " + app.packageName);
6934 }
6935 }
6936 mProfileApp = processName;
6937 mProfileFile = profileFile;
6938 if (mProfileFd != null) {
6939 try {
6940 mProfileFd.close();
6941 } catch (IOException e) {
6942 }
6943 mProfileFd = null;
6944 }
6945 mProfileFd = profileFd;
6946 mProfileType = 0;
6947 mAutoStopProfiler = autoStopProfiler;
6948 }
6949 }
6950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 public void setAlwaysFinish(boolean enabled) {
6952 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6953 "setAlwaysFinish()");
6954
6955 Settings.System.putInt(
6956 mContext.getContentResolver(),
6957 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6958
6959 synchronized (this) {
6960 mAlwaysFinishActivities = enabled;
6961 }
6962 }
6963
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006964 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006966 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006968 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 }
6970 }
6971
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006972 public boolean isUserAMonkey() {
6973 // For now the fact that there is a controller implies
6974 // we have a monkey.
6975 synchronized (this) {
6976 return mController != null;
6977 }
6978 }
6979
Jeff Sharkeya4620792011-05-20 15:29:23 -07006980 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006981 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6982 "registerProcessObserver()");
6983 synchronized (this) {
6984 mProcessObservers.register(observer);
6985 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006986 }
6987
6988 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006989 synchronized (this) {
6990 mProcessObservers.unregister(observer);
6991 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006992 }
6993
Daniel Sandler69a48172010-06-23 16:29:36 -04006994 public void setImmersive(IBinder token, boolean immersive) {
6995 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006996 ActivityRecord r = mMainStack.isInStackLocked(token);
6997 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006998 throw new IllegalArgumentException();
6999 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007000 r.immersive = immersive;
7001 }
7002 }
7003
7004 public boolean isImmersive(IBinder token) {
7005 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007006 ActivityRecord r = mMainStack.isInStackLocked(token);
7007 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007008 throw new IllegalArgumentException();
7009 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007010 return r.immersive;
7011 }
7012 }
7013
7014 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007015 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007016 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007017 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007018 return (r != null) ? r.immersive : false;
7019 }
7020 }
7021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 public final void enterSafeMode() {
7023 synchronized(this) {
7024 // It only makes sense to do this before the system is ready
7025 // and started launching other packages.
7026 if (!mSystemReady) {
7027 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007028 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 } catch (RemoteException e) {
7030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 }
7032 }
7033 }
7034
Jeff Brownb09abc12011-01-13 21:08:27 -08007035 public final void showSafeModeOverlay() {
7036 View v = LayoutInflater.from(mContext).inflate(
7037 com.android.internal.R.layout.safe_mode, null);
7038 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7039 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7040 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7041 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7042 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7043 lp.format = v.getBackground().getOpacity();
7044 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7045 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7046 ((WindowManager)mContext.getSystemService(
7047 Context.WINDOW_SERVICE)).addView(v, lp);
7048 }
7049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 public void noteWakeupAlarm(IIntentSender sender) {
7051 if (!(sender instanceof PendingIntentRecord)) {
7052 return;
7053 }
7054 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7055 synchronized (stats) {
7056 if (mBatteryStatsService.isOnBattery()) {
7057 mBatteryStatsService.enforceCallingPermission();
7058 PendingIntentRecord rec = (PendingIntentRecord)sender;
7059 int MY_UID = Binder.getCallingUid();
7060 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7061 BatteryStatsImpl.Uid.Pkg pkg =
7062 stats.getPackageStatsLocked(uid, rec.key.packageName);
7063 pkg.incWakeupsLocked();
7064 }
7065 }
7066 }
7067
Dianne Hackborn64825172011-03-02 21:32:58 -08007068 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007070 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007071 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007072 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 // XXX Note: don't acquire main activity lock here, because the window
7074 // manager calls in with its locks held.
7075
7076 boolean killed = false;
7077 synchronized (mPidsSelfLocked) {
7078 int[] types = new int[pids.length];
7079 int worstType = 0;
7080 for (int i=0; i<pids.length; i++) {
7081 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7082 if (proc != null) {
7083 int type = proc.setAdj;
7084 types[i] = type;
7085 if (type > worstType) {
7086 worstType = type;
7087 }
7088 }
7089 }
7090
Dianne Hackborn64825172011-03-02 21:32:58 -08007091 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007093 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7094 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007095 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007097
7098 // If this is not a secure call, don't let it kill processes that
7099 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007100 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7101 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007102 }
7103
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007104 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 for (int i=0; i<pids.length; i++) {
7106 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7107 if (proc == null) {
7108 continue;
7109 }
7110 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007111 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007112 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007113 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7114 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007116 proc.killedBackground = true;
7117 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 }
7119 }
7120 }
7121 return killed;
7122 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007123
7124 @Override
7125 public boolean killProcessesBelowForeground(String reason) {
7126 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7127 throw new SecurityException("killProcessesBelowForeground() only available to system");
7128 }
7129
7130 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7131 }
7132
7133 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7134 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7135 throw new SecurityException("killProcessesBelowAdj() only available to system");
7136 }
7137
7138 boolean killed = false;
7139 synchronized (mPidsSelfLocked) {
7140 final int size = mPidsSelfLocked.size();
7141 for (int i = 0; i < size; i++) {
7142 final int pid = mPidsSelfLocked.keyAt(i);
7143 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7144 if (proc == null) continue;
7145
7146 final int adj = proc.setAdj;
7147 if (adj > belowAdj && !proc.killedBackground) {
7148 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7149 EventLog.writeEvent(
7150 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7151 killed = true;
7152 proc.killedBackground = true;
7153 Process.killProcessQuiet(pid);
7154 }
7155 }
7156 }
7157 return killed;
7158 }
7159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 public final void startRunning(String pkg, String cls, String action,
7161 String data) {
7162 synchronized(this) {
7163 if (mStartRunning) {
7164 return;
7165 }
7166 mStartRunning = true;
7167 mTopComponent = pkg != null && cls != null
7168 ? new ComponentName(pkg, cls) : null;
7169 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7170 mTopData = data;
7171 if (!mSystemReady) {
7172 return;
7173 }
7174 }
7175
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007176 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 }
7178
7179 private void retrieveSettings() {
7180 final ContentResolver resolver = mContext.getContentResolver();
7181 String debugApp = Settings.System.getString(
7182 resolver, Settings.System.DEBUG_APP);
7183 boolean waitForDebugger = Settings.System.getInt(
7184 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7185 boolean alwaysFinishActivities = Settings.System.getInt(
7186 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7187
7188 Configuration configuration = new Configuration();
7189 Settings.System.getConfiguration(resolver, configuration);
7190
7191 synchronized (this) {
7192 mDebugApp = mOrigDebugApp = debugApp;
7193 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7194 mAlwaysFinishActivities = alwaysFinishActivities;
7195 // This happens before any activities are started, so we can
7196 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007197 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007198 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 }
7200 }
7201
7202 public boolean testIsSystemReady() {
7203 // no need to synchronize(this) just to read & return the value
7204 return mSystemReady;
7205 }
7206
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007207 private static File getCalledPreBootReceiversFile() {
7208 File dataDir = Environment.getDataDirectory();
7209 File systemDir = new File(dataDir, "system");
7210 File fname = new File(systemDir, "called_pre_boots.dat");
7211 return fname;
7212 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007213
7214 static final int LAST_DONE_VERSION = 10000;
7215
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007216 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7217 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7218 File file = getCalledPreBootReceiversFile();
7219 FileInputStream fis = null;
7220 try {
7221 fis = new FileInputStream(file);
7222 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007223 int fvers = dis.readInt();
7224 if (fvers == LAST_DONE_VERSION) {
7225 String vers = dis.readUTF();
7226 String codename = dis.readUTF();
7227 String build = dis.readUTF();
7228 if (android.os.Build.VERSION.RELEASE.equals(vers)
7229 && android.os.Build.VERSION.CODENAME.equals(codename)
7230 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7231 int num = dis.readInt();
7232 while (num > 0) {
7233 num--;
7234 String pkg = dis.readUTF();
7235 String cls = dis.readUTF();
7236 lastDoneReceivers.add(new ComponentName(pkg, cls));
7237 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007238 }
7239 }
7240 } catch (FileNotFoundException e) {
7241 } catch (IOException e) {
7242 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7243 } finally {
7244 if (fis != null) {
7245 try {
7246 fis.close();
7247 } catch (IOException e) {
7248 }
7249 }
7250 }
7251 return lastDoneReceivers;
7252 }
7253
7254 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7255 File file = getCalledPreBootReceiversFile();
7256 FileOutputStream fos = null;
7257 DataOutputStream dos = null;
7258 try {
7259 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7260 fos = new FileOutputStream(file);
7261 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007262 dos.writeInt(LAST_DONE_VERSION);
7263 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007264 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007265 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007266 dos.writeInt(list.size());
7267 for (int i=0; i<list.size(); i++) {
7268 dos.writeUTF(list.get(i).getPackageName());
7269 dos.writeUTF(list.get(i).getClassName());
7270 }
7271 } catch (IOException e) {
7272 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7273 file.delete();
7274 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007275 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007276 if (dos != null) {
7277 try {
7278 dos.close();
7279 } catch (IOException e) {
7280 // TODO Auto-generated catch block
7281 e.printStackTrace();
7282 }
7283 }
7284 }
7285 }
7286
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007287 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 synchronized(this) {
7289 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007290 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 return;
7292 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007293
7294 // Check to see if there are any update receivers to run.
7295 if (!mDidUpdate) {
7296 if (mWaitingUpdate) {
7297 return;
7298 }
7299 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7300 List<ResolveInfo> ris = null;
7301 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007302 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007303 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007304 } catch (RemoteException e) {
7305 }
7306 if (ris != null) {
7307 for (int i=ris.size()-1; i>=0; i--) {
7308 if ((ris.get(i).activityInfo.applicationInfo.flags
7309 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7310 ris.remove(i);
7311 }
7312 }
7313 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007314
7315 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7316
7317 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007318 for (int i=0; i<ris.size(); i++) {
7319 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007320 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7321 if (lastDoneReceivers.contains(comp)) {
7322 ris.remove(i);
7323 i--;
7324 }
7325 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007326
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007327 for (int i=0; i<ris.size(); i++) {
7328 ActivityInfo ai = ris.get(i).activityInfo;
7329 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7330 doneReceivers.add(comp);
7331 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007332 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007333 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007334 finisher = new IIntentReceiver.Stub() {
7335 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007336 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007337 boolean sticky) {
7338 // The raw IIntentReceiver interface is called
7339 // with the AM lock held, so redispatch to
7340 // execute our code without the lock.
7341 mHandler.post(new Runnable() {
7342 public void run() {
7343 synchronized (ActivityManagerService.this) {
7344 mDidUpdate = true;
7345 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007346 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007347 showBootMessage(mContext.getText(
7348 R.string.android_upgrading_complete),
7349 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007350 systemReady(goingCallback);
7351 }
7352 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007353 }
7354 };
7355 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007356 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007357 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007358 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007359 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007360 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007361 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007362 mWaitingUpdate = true;
7363 }
7364 }
7365 }
7366 if (mWaitingUpdate) {
7367 return;
7368 }
7369 mDidUpdate = true;
7370 }
7371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007372 mSystemReady = true;
7373 if (!mStartRunning) {
7374 return;
7375 }
7376 }
7377
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007378 ArrayList<ProcessRecord> procsToKill = null;
7379 synchronized(mPidsSelfLocked) {
7380 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7381 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7382 if (!isAllowedWhileBooting(proc.info)){
7383 if (procsToKill == null) {
7384 procsToKill = new ArrayList<ProcessRecord>();
7385 }
7386 procsToKill.add(proc);
7387 }
7388 }
7389 }
7390
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007391 synchronized(this) {
7392 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007393 for (int i=procsToKill.size()-1; i>=0; i--) {
7394 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007395 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007396 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007397 }
7398 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007399
7400 // Now that we have cleaned up any update processes, we
7401 // are ready to start launching real processes and know that
7402 // we won't trample on them any more.
7403 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007404 }
7405
Joe Onorato8a9b2202010-02-26 18:56:32 -08007406 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007407 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007408 SystemClock.uptimeMillis());
7409
7410 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007411 // Make sure we have no pre-ready processes sitting around.
7412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7414 ResolveInfo ri = mContext.getPackageManager()
7415 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007416 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 CharSequence errorMsg = null;
7418 if (ri != null) {
7419 ActivityInfo ai = ri.activityInfo;
7420 ApplicationInfo app = ai.applicationInfo;
7421 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7422 mTopAction = Intent.ACTION_FACTORY_TEST;
7423 mTopData = null;
7424 mTopComponent = new ComponentName(app.packageName,
7425 ai.name);
7426 } else {
7427 errorMsg = mContext.getResources().getText(
7428 com.android.internal.R.string.factorytest_not_system);
7429 }
7430 } else {
7431 errorMsg = mContext.getResources().getText(
7432 com.android.internal.R.string.factorytest_no_action);
7433 }
7434 if (errorMsg != null) {
7435 mTopAction = null;
7436 mTopData = null;
7437 mTopComponent = null;
7438 Message msg = Message.obtain();
7439 msg.what = SHOW_FACTORY_ERROR_MSG;
7440 msg.getData().putCharSequence("msg", errorMsg);
7441 mHandler.sendMessage(msg);
7442 }
7443 }
7444 }
7445
7446 retrieveSettings();
7447
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007448 if (goingCallback != null) goingCallback.run();
7449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007450 synchronized (this) {
7451 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7452 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007453 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007454 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 if (apps != null) {
7456 int N = apps.size();
7457 int i;
7458 for (i=0; i<N; i++) {
7459 ApplicationInfo info
7460 = (ApplicationInfo)apps.get(i);
7461 if (info != null &&
7462 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007463 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 }
7465 }
7466 }
7467 } catch (RemoteException ex) {
7468 // pm is in same process, this will never happen.
7469 }
7470 }
7471
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007472 // Start up initial activity.
7473 mBooting = true;
7474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007475 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007476 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007477 Message msg = Message.obtain();
7478 msg.what = SHOW_UID_ERROR_MSG;
7479 mHandler.sendMessage(msg);
7480 }
7481 } catch (RemoteException e) {
7482 }
7483
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007484 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 }
7486 }
7487
Dan Egnorb7f03672009-12-09 16:22:32 -08007488 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007489 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007490 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007491 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007492 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 startAppProblemLocked(app);
7494 app.stopFreezingAllLocked();
7495 return handleAppCrashLocked(app);
7496 }
7497
Dan Egnorb7f03672009-12-09 16:22:32 -08007498 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007499 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007501 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007502 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7503 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007504 startAppProblemLocked(app);
7505 app.stopFreezingAllLocked();
7506 }
7507
7508 /**
7509 * Generate a process error record, suitable for attachment to a ProcessRecord.
7510 *
7511 * @param app The ProcessRecord in which the error occurred.
7512 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7513 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007514 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007515 * @param shortMsg Short message describing the crash.
7516 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007517 * @param stackTrace Full crash stack trace, may be null.
7518 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 * @return Returns a fully-formed AppErrorStateInfo record.
7520 */
7521 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007522 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 report.condition = condition;
7526 report.processName = app.processName;
7527 report.pid = app.pid;
7528 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007529 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 report.shortMsg = shortMsg;
7531 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007532 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533
7534 return report;
7535 }
7536
Dan Egnor42471dd2010-01-07 17:25:22 -08007537 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 synchronized (this) {
7539 app.crashing = false;
7540 app.crashingReport = null;
7541 app.notResponding = false;
7542 app.notRespondingReport = null;
7543 if (app.anrDialog == fromDialog) {
7544 app.anrDialog = null;
7545 }
7546 if (app.waitDialog == fromDialog) {
7547 app.waitDialog = null;
7548 }
7549 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007550 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007551 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007552 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7553 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007554 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 }
7557 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007558
Dan Egnorb7f03672009-12-09 16:22:32 -08007559 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007560 if (mHeadless) {
7561 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7562 return false;
7563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 long now = SystemClock.uptimeMillis();
7565
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007566 Long crashTime;
7567 if (!app.isolated) {
7568 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7569 } else {
7570 crashTime = null;
7571 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007572 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007574 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007576 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007577 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007578 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7579 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007581 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007583 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 }
7585 }
7586 if (!app.persistent) {
7587 // We don't want to start this process again until the user
7588 // explicitly does so... but for persistent process, we really
7589 // need to keep it running. If a persistent process is actually
7590 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007591 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007593 if (!app.isolated) {
7594 // XXX We don't have a way to mark isolated processes
7595 // as bad, since they don't have a peristent identity.
7596 mBadProcesses.put(app.info.processName, app.uid, now);
7597 mProcessCrashTimes.remove(app.info.processName, app.uid);
7598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007601 // Don't let services in this process be restarted and potentially
7602 // annoy the user repeatedly. Unless it is persistent, since those
7603 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007604 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007605 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 return false;
7607 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007608 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007609 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007610 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007611 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007612 // If the top running activity is from this crashing
7613 // process, then terminate it to avoid getting in a loop.
7614 Slog.w(TAG, " Force finishing activity "
7615 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007616 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007617 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007618 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007619 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007620 // stopped, to avoid a situation where one will get
7621 // re-start our crashing activity once it gets resumed again.
7622 index--;
7623 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007624 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007625 if (r.state == ActivityState.RESUMED
7626 || r.state == ActivityState.PAUSING
7627 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007628 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007629 Slog.w(TAG, " Force finishing activity "
7630 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007631 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007632 Activity.RESULT_CANCELED, null, "crashed");
7633 }
7634 }
7635 }
7636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 }
7638
7639 // Bump up the crash count of any services currently running in the proc.
7640 if (app.services.size() != 0) {
7641 // Any services running in the application need to be placed
7642 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007643 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007645 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 sr.crashCount++;
7647 }
7648 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007649
7650 // If the crashing process is what we consider to be the "home process" and it has been
7651 // replaced by a third-party app, clear the package preferred activities from packages
7652 // with a home activity running in the process to prevent a repeatedly crashing app
7653 // from blocking the user to manually clear the list.
7654 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7655 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7656 Iterator it = mHomeProcess.activities.iterator();
7657 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007658 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007659 if (r.isHomeActivity) {
7660 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7661 try {
7662 ActivityThread.getPackageManager()
7663 .clearPackagePreferredActivities(r.packageName);
7664 } catch (RemoteException c) {
7665 // pm is in same process, this will never happen.
7666 }
7667 }
7668 }
7669 }
7670
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007671 if (!app.isolated) {
7672 // XXX Can't keep track of crash times for isolated processes,
7673 // because they don't have a perisistent identity.
7674 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7675 }
7676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 return true;
7678 }
7679
7680 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007681 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7682 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 skipCurrentReceiverLocked(app);
7684 }
7685
7686 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007687 for (BroadcastQueue queue : mBroadcastQueues) {
7688 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 }
7690 }
7691
Dan Egnor60d87622009-12-16 16:32:58 -08007692 /**
7693 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7694 * The application process will exit immediately after this call returns.
7695 * @param app object of the crashing app, null for the system server
7696 * @param crashInfo describing the exception
7697 */
7698 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007699 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007700 final String processName = app == null ? "system_server"
7701 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007702
7703 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007704 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007705 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007706 crashInfo.exceptionClassName,
7707 crashInfo.exceptionMessage,
7708 crashInfo.throwFileName,
7709 crashInfo.throwLineNumber);
7710
Jeff Sharkeya353d262011-10-28 11:12:06 -07007711 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007712
7713 crashApplication(r, crashInfo);
7714 }
7715
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007716 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007717 IBinder app,
7718 int violationMask,
7719 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007720 ProcessRecord r = findAppProcess(app, "StrictMode");
7721 if (r == null) {
7722 return;
7723 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007724
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007725 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007726 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007727 boolean logIt = true;
7728 synchronized (mAlreadyLoggedViolatedStacks) {
7729 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7730 logIt = false;
7731 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007732 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007733 // the relative pain numbers, without logging all
7734 // the stack traces repeatedly. We'd want to do
7735 // likewise in the client code, which also does
7736 // dup suppression, before the Binder call.
7737 } else {
7738 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7739 mAlreadyLoggedViolatedStacks.clear();
7740 }
7741 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7742 }
7743 }
7744 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007745 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007746 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007747 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007748
7749 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7750 AppErrorResult result = new AppErrorResult();
7751 synchronized (this) {
7752 final long origId = Binder.clearCallingIdentity();
7753
7754 Message msg = Message.obtain();
7755 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7756 HashMap<String, Object> data = new HashMap<String, Object>();
7757 data.put("result", result);
7758 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007759 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007760 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007761 msg.obj = data;
7762 mHandler.sendMessage(msg);
7763
7764 Binder.restoreCallingIdentity(origId);
7765 }
7766 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007767 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007768 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007769 }
7770
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007771 // Depending on the policy in effect, there could be a bunch of
7772 // these in quick succession so we try to batch these together to
7773 // minimize disk writes, number of dropbox entries, and maximize
7774 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007775 private void logStrictModeViolationToDropBox(
7776 ProcessRecord process,
7777 StrictMode.ViolationInfo info) {
7778 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007779 return;
7780 }
7781 final boolean isSystemApp = process == null ||
7782 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7783 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007784 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007785 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7786 final DropBoxManager dbox = (DropBoxManager)
7787 mContext.getSystemService(Context.DROPBOX_SERVICE);
7788
7789 // Exit early if the dropbox isn't configured to accept this report type.
7790 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7791
7792 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007793 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007794 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7795 synchronized (sb) {
7796 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007797 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007798 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7799 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007800 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7801 if (info.violationNumThisLoop != 0) {
7802 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7803 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007804 if (info.numAnimationsRunning != 0) {
7805 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7806 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007807 if (info.broadcastIntentAction != null) {
7808 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7809 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007810 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007811 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007812 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007813 if (info.numInstances != -1) {
7814 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7815 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007816 if (info.tags != null) {
7817 for (String tag : info.tags) {
7818 sb.append("Span-Tag: ").append(tag).append("\n");
7819 }
7820 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007821 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007822 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7823 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007824 }
7825 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007826
7827 // Only buffer up to ~64k. Various logging bits truncate
7828 // things at 128k.
7829 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007830 }
7831
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007832 // Flush immediately if the buffer's grown too large, or this
7833 // is a non-system app. Non-system apps are isolated with a
7834 // different tag & policy and not batched.
7835 //
7836 // Batching is useful during internal testing with
7837 // StrictMode settings turned up high. Without batching,
7838 // thousands of separate files could be created on boot.
7839 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007840 new Thread("Error dump: " + dropboxTag) {
7841 @Override
7842 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007843 String report;
7844 synchronized (sb) {
7845 report = sb.toString();
7846 sb.delete(0, sb.length());
7847 sb.trimToSize();
7848 }
7849 if (report.length() != 0) {
7850 dbox.addText(dropboxTag, report);
7851 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007852 }
7853 }.start();
7854 return;
7855 }
7856
7857 // System app batching:
7858 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007859 // An existing dropbox-writing thread is outstanding, so
7860 // we don't need to start it up. The existing thread will
7861 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007862 return;
7863 }
7864
7865 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7866 // (After this point, we shouldn't access AMS internal data structures.)
7867 new Thread("Error dump: " + dropboxTag) {
7868 @Override
7869 public void run() {
7870 // 5 second sleep to let stacks arrive and be batched together
7871 try {
7872 Thread.sleep(5000); // 5 seconds
7873 } catch (InterruptedException e) {}
7874
7875 String errorReport;
7876 synchronized (mStrictModeBuffer) {
7877 errorReport = mStrictModeBuffer.toString();
7878 if (errorReport.length() == 0) {
7879 return;
7880 }
7881 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7882 mStrictModeBuffer.trimToSize();
7883 }
7884 dbox.addText(dropboxTag, errorReport);
7885 }
7886 }.start();
7887 }
7888
Dan Egnor60d87622009-12-16 16:32:58 -08007889 /**
7890 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7891 * @param app object of the crashing app, null for the system server
7892 * @param tag reported by the caller
7893 * @param crashInfo describing the context of the error
7894 * @return true if the process should exit immediately (WTF is fatal)
7895 */
7896 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007897 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007898 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007899 final String processName = app == null ? "system_server"
7900 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007901
7902 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007903 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007904 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007905 tag, crashInfo.exceptionMessage);
7906
Jeff Sharkeya353d262011-10-28 11:12:06 -07007907 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007908
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007909 if (r != null && r.pid != Process.myPid() &&
7910 Settings.Secure.getInt(mContext.getContentResolver(),
7911 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007912 crashApplication(r, crashInfo);
7913 return true;
7914 } else {
7915 return false;
7916 }
7917 }
7918
7919 /**
7920 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7921 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7922 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007923 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007924 if (app == null) {
7925 return null;
7926 }
7927
7928 synchronized (this) {
7929 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7930 final int NA = apps.size();
7931 for (int ia=0; ia<NA; ia++) {
7932 ProcessRecord p = apps.valueAt(ia);
7933 if (p.thread != null && p.thread.asBinder() == app) {
7934 return p;
7935 }
7936 }
7937 }
7938
Dianne Hackborncb44d962011-03-10 17:02:27 -08007939 Slog.w(TAG, "Can't find mystery application for " + reason
7940 + " from pid=" + Binder.getCallingPid()
7941 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007942 return null;
7943 }
7944 }
7945
7946 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007947 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7948 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007949 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007950 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7951 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007952 // Watchdog thread ends up invoking this function (with
7953 // a null ProcessRecord) to add the stack file to dropbox.
7954 // Do not acquire a lock on this (am) in such cases, as it
7955 // could cause a potential deadlock, if and when watchdog
7956 // is invoked due to unavailability of lock on am and it
7957 // would prevent watchdog from killing system_server.
7958 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007959 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007960 return;
7961 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007962 // Note: ProcessRecord 'process' is guarded by the service
7963 // instance. (notably process.pkgList, which could otherwise change
7964 // concurrently during execution of this method)
7965 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007966 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007967 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007968 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007969 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7970 for (String pkg : process.pkgList) {
7971 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007972 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007973 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007974 if (pi != null) {
7975 sb.append(" v").append(pi.versionCode);
7976 if (pi.versionName != null) {
7977 sb.append(" (").append(pi.versionName).append(")");
7978 }
7979 }
7980 } catch (RemoteException e) {
7981 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007982 }
Dan Egnora455d192010-03-12 08:52:28 -08007983 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007984 }
Dan Egnora455d192010-03-12 08:52:28 -08007985 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007986 }
7987
7988 private static String processClass(ProcessRecord process) {
7989 if (process == null || process.pid == MY_PID) {
7990 return "system_server";
7991 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7992 return "system_app";
7993 } else {
7994 return "data_app";
7995 }
7996 }
7997
7998 /**
7999 * Write a description of an error (crash, WTF, ANR) to the drop box.
8000 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8001 * @param process which caused the error, null means the system server
8002 * @param activity which triggered the error, null if unknown
8003 * @param parent activity related to the error, null if unknown
8004 * @param subject line related to the error, null if absent
8005 * @param report in long form describing the error, null if absent
8006 * @param logFile to include in the report, null if none
8007 * @param crashInfo giving an application stack trace, null if absent
8008 */
8009 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008010 ProcessRecord process, String processName, ActivityRecord activity,
8011 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008012 final String report, final File logFile,
8013 final ApplicationErrorReport.CrashInfo crashInfo) {
8014 // NOTE -- this must never acquire the ActivityManagerService lock,
8015 // otherwise the watchdog may be prevented from resetting the system.
8016
8017 final String dropboxTag = processClass(process) + "_" + eventType;
8018 final DropBoxManager dbox = (DropBoxManager)
8019 mContext.getSystemService(Context.DROPBOX_SERVICE);
8020
8021 // Exit early if the dropbox isn't configured to accept this report type.
8022 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8023
8024 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008025 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008026 if (activity != null) {
8027 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8028 }
8029 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8030 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8031 }
8032 if (parent != null && parent != activity) {
8033 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8034 }
8035 if (subject != null) {
8036 sb.append("Subject: ").append(subject).append("\n");
8037 }
8038 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008039 if (Debug.isDebuggerConnected()) {
8040 sb.append("Debugger: Connected\n");
8041 }
Dan Egnora455d192010-03-12 08:52:28 -08008042 sb.append("\n");
8043
8044 // Do the rest in a worker thread to avoid blocking the caller on I/O
8045 // (After this point, we shouldn't access AMS internal data structures.)
8046 Thread worker = new Thread("Error dump: " + dropboxTag) {
8047 @Override
8048 public void run() {
8049 if (report != null) {
8050 sb.append(report);
8051 }
8052 if (logFile != null) {
8053 try {
8054 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8055 } catch (IOException e) {
8056 Slog.e(TAG, "Error reading " + logFile, e);
8057 }
8058 }
8059 if (crashInfo != null && crashInfo.stackTrace != null) {
8060 sb.append(crashInfo.stackTrace);
8061 }
8062
8063 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8064 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8065 if (lines > 0) {
8066 sb.append("\n");
8067
8068 // Merge several logcat streams, and take the last N lines
8069 InputStreamReader input = null;
8070 try {
8071 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8072 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8073 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8074
8075 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8076 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8077 input = new InputStreamReader(logcat.getInputStream());
8078
8079 int num;
8080 char[] buf = new char[8192];
8081 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8082 } catch (IOException e) {
8083 Slog.e(TAG, "Error running logcat", e);
8084 } finally {
8085 if (input != null) try { input.close(); } catch (IOException e) {}
8086 }
8087 }
8088
8089 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008090 }
Dan Egnora455d192010-03-12 08:52:28 -08008091 };
8092
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008093 if (process == null) {
8094 // If process is null, we are being called from some internal code
8095 // and may be about to die -- run this synchronously.
8096 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008097 } else {
8098 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008099 }
8100 }
8101
8102 /**
8103 * Bring up the "unexpected error" dialog box for a crashing app.
8104 * Deal with edge cases (intercepts from instrumented applications,
8105 * ActivityController, error intent receivers, that sort of thing).
8106 * @param r the application crashing
8107 * @param crashInfo describing the failure
8108 */
8109 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008110 long timeMillis = System.currentTimeMillis();
8111 String shortMsg = crashInfo.exceptionClassName;
8112 String longMsg = crashInfo.exceptionMessage;
8113 String stackTrace = crashInfo.stackTrace;
8114 if (shortMsg != null && longMsg != null) {
8115 longMsg = shortMsg + ": " + longMsg;
8116 } else if (shortMsg != null) {
8117 longMsg = shortMsg;
8118 }
8119
Dan Egnor60d87622009-12-16 16:32:58 -08008120 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008121 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008122 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 try {
8124 String name = r != null ? r.processName : null;
8125 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008126 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008127 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008128 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008129 + " at watcher's request");
8130 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008131 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 }
8133 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008134 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 }
8136 }
8137
8138 final long origId = Binder.clearCallingIdentity();
8139
8140 // If this process is running instrumentation, finish it.
8141 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008142 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008143 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008144 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8145 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 Bundle info = new Bundle();
8147 info.putString("shortMsg", shortMsg);
8148 info.putString("longMsg", longMsg);
8149 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8150 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008151 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008152 }
8153
Dan Egnor60d87622009-12-16 16:32:58 -08008154 // If we can't identify the process or it's already exceeded its crash quota,
8155 // quit right away without showing a crash dialog.
8156 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008158 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 }
8160
8161 Message msg = Message.obtain();
8162 msg.what = SHOW_ERROR_MSG;
8163 HashMap data = new HashMap();
8164 data.put("result", result);
8165 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 msg.obj = data;
8167 mHandler.sendMessage(msg);
8168
8169 Binder.restoreCallingIdentity(origId);
8170 }
8171
8172 int res = result.get();
8173
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008174 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008176 if (r != null && !r.isolated) {
8177 // XXX Can't keep track of crash time for isolated processes,
8178 // since they don't have a persistent identity.
8179 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 SystemClock.uptimeMillis());
8181 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008182 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008183 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008184 }
8185 }
8186
8187 if (appErrorIntent != null) {
8188 try {
8189 mContext.startActivity(appErrorIntent);
8190 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008191 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008195
8196 Intent createAppErrorIntentLocked(ProcessRecord r,
8197 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8198 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008199 if (report == null) {
8200 return null;
8201 }
8202 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8203 result.setComponent(r.errorReportReceiver);
8204 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8205 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8206 return result;
8207 }
8208
Dan Egnorb7f03672009-12-09 16:22:32 -08008209 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8210 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008211 if (r.errorReportReceiver == null) {
8212 return null;
8213 }
8214
8215 if (!r.crashing && !r.notResponding) {
8216 return null;
8217 }
8218
Dan Egnorb7f03672009-12-09 16:22:32 -08008219 ApplicationErrorReport report = new ApplicationErrorReport();
8220 report.packageName = r.info.packageName;
8221 report.installerPackageName = r.errorReportReceiver.getPackageName();
8222 report.processName = r.processName;
8223 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008224 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008225
Dan Egnorb7f03672009-12-09 16:22:32 -08008226 if (r.crashing) {
8227 report.type = ApplicationErrorReport.TYPE_CRASH;
8228 report.crashInfo = crashInfo;
8229 } else if (r.notResponding) {
8230 report.type = ApplicationErrorReport.TYPE_ANR;
8231 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008232
Dan Egnorb7f03672009-12-09 16:22:32 -08008233 report.anrInfo.activity = r.notRespondingReport.tag;
8234 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8235 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008236 }
8237
Dan Egnorb7f03672009-12-09 16:22:32 -08008238 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008239 }
8240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008241 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008242 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 // assume our apps are happy - lazy create the list
8244 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8245
8246 synchronized (this) {
8247
8248 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008249 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8250 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8252 // This one's in trouble, so we'll generate a report for it
8253 // crashes are higher priority (in case there's a crash *and* an anr)
8254 ActivityManager.ProcessErrorStateInfo report = null;
8255 if (app.crashing) {
8256 report = app.crashingReport;
8257 } else if (app.notResponding) {
8258 report = app.notRespondingReport;
8259 }
8260
8261 if (report != null) {
8262 if (errList == null) {
8263 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8264 }
8265 errList.add(report);
8266 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008267 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 " crashing = " + app.crashing +
8269 " notResponding = " + app.notResponding);
8270 }
8271 }
8272 }
8273 }
8274
8275 return errList;
8276 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008277
8278 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008279 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008280 if (currApp != null) {
8281 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8282 }
8283 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008284 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8285 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008286 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8287 if (currApp != null) {
8288 currApp.lru = 0;
8289 }
8290 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008291 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008292 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8293 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8294 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8295 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8296 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8297 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8298 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8299 } else {
8300 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8301 }
8302 }
8303
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008304 private void fillInProcMemInfo(ProcessRecord app,
8305 ActivityManager.RunningAppProcessInfo outInfo) {
8306 outInfo.pid = app.pid;
8307 outInfo.uid = app.info.uid;
8308 if (mHeavyWeightProcess == app) {
8309 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8310 }
8311 if (app.persistent) {
8312 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8313 }
8314 outInfo.lastTrimLevel = app.trimMemoryLevel;
8315 int adj = app.curAdj;
8316 outInfo.importance = oomAdjToImportance(adj, outInfo);
8317 outInfo.importanceReasonCode = app.adjTypeCode;
8318 }
8319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008321 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 // Lazy instantiation of list
8323 List<ActivityManager.RunningAppProcessInfo> runList = null;
8324 synchronized (this) {
8325 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008326 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8327 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8329 // Generate process state info for running application
8330 ActivityManager.RunningAppProcessInfo currApp =
8331 new ActivityManager.RunningAppProcessInfo(app.processName,
8332 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008333 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008334 if (app.adjSource instanceof ProcessRecord) {
8335 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008336 currApp.importanceReasonImportance = oomAdjToImportance(
8337 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008338 } else if (app.adjSource instanceof ActivityRecord) {
8339 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008340 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8341 }
8342 if (app.adjTarget instanceof ComponentName) {
8343 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8344 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008345 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 // + " lru=" + currApp.lru);
8347 if (runList == null) {
8348 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8349 }
8350 runList.add(currApp);
8351 }
8352 }
8353 }
8354 return runList;
8355 }
8356
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008357 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008358 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008359 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8360 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8361 if (runningApps != null && runningApps.size() > 0) {
8362 Set<String> extList = new HashSet<String>();
8363 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8364 if (app.pkgList != null) {
8365 for (String pkg : app.pkgList) {
8366 extList.add(pkg);
8367 }
8368 }
8369 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008370 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008371 for (String pkg : extList) {
8372 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008373 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008374 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8375 retList.add(info);
8376 }
8377 } catch (RemoteException e) {
8378 }
8379 }
8380 }
8381 return retList;
8382 }
8383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008384 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008385 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8386 enforceNotIsolatedCaller("getMyMemoryState");
8387 synchronized (this) {
8388 ProcessRecord proc;
8389 synchronized (mPidsSelfLocked) {
8390 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8391 }
8392 fillInProcMemInfo(proc, outInfo);
8393 }
8394 }
8395
8396 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008397 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008398 if (checkCallingPermission(android.Manifest.permission.DUMP)
8399 != PackageManager.PERMISSION_GRANTED) {
8400 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8401 + Binder.getCallingPid()
8402 + ", uid=" + Binder.getCallingUid()
8403 + " without permission "
8404 + android.Manifest.permission.DUMP);
8405 return;
8406 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008407
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008408 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008409 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008410 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008411
8412 int opti = 0;
8413 while (opti < args.length) {
8414 String opt = args[opti];
8415 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8416 break;
8417 }
8418 opti++;
8419 if ("-a".equals(opt)) {
8420 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008421 } else if ("-c".equals(opt)) {
8422 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008423 } else if ("-h".equals(opt)) {
8424 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008425 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008426 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008427 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008428 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8429 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8430 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008431 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008432 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008433 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008434 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008435 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008436 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008437 pw.println(" all: dump all activities");
8438 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008439 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008440 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8441 pw.println(" a partial substring in a component name, a");
8442 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008443 pw.println(" -a: include all available server state.");
8444 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008446 } else {
8447 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008450
8451 long origId = Binder.clearCallingIdentity();
8452 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008453 // Is the caller requesting to dump a particular piece of data?
8454 if (opti < args.length) {
8455 String cmd = args[opti];
8456 opti++;
8457 if ("activities".equals(cmd) || "a".equals(cmd)) {
8458 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008459 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008460 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008461 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008462 String[] newArgs;
8463 String name;
8464 if (opti >= args.length) {
8465 name = null;
8466 newArgs = EMPTY_STRING_ARRAY;
8467 } else {
8468 name = args[opti];
8469 opti++;
8470 newArgs = new String[args.length - opti];
8471 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8472 args.length - opti);
8473 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008474 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008475 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008476 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008477 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008478 String[] newArgs;
8479 String name;
8480 if (opti >= args.length) {
8481 name = null;
8482 newArgs = EMPTY_STRING_ARRAY;
8483 } else {
8484 name = args[opti];
8485 opti++;
8486 newArgs = new String[args.length - opti];
8487 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8488 args.length - opti);
8489 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008490 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008491 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008492 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008493 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008494 String[] newArgs;
8495 String name;
8496 if (opti >= args.length) {
8497 name = null;
8498 newArgs = EMPTY_STRING_ARRAY;
8499 } else {
8500 name = args[opti];
8501 opti++;
8502 newArgs = new String[args.length - opti];
8503 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8504 args.length - opti);
8505 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008506 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008507 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008508 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008509 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8510 synchronized (this) {
8511 dumpOomLocked(fd, pw, args, opti, true);
8512 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008513 } else if ("provider".equals(cmd)) {
8514 String[] newArgs;
8515 String name;
8516 if (opti >= args.length) {
8517 name = null;
8518 newArgs = EMPTY_STRING_ARRAY;
8519 } else {
8520 name = args[opti];
8521 opti++;
8522 newArgs = new String[args.length - opti];
8523 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8524 }
8525 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8526 pw.println("No providers match: " + name);
8527 pw.println("Use -h for help.");
8528 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008529 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8530 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008531 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008533 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008534 String[] newArgs;
8535 String name;
8536 if (opti >= args.length) {
8537 name = null;
8538 newArgs = EMPTY_STRING_ARRAY;
8539 } else {
8540 name = args[opti];
8541 opti++;
8542 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008543 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8544 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008545 }
8546 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8547 pw.println("No services match: " + name);
8548 pw.println("Use -h for help.");
8549 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008550 } else if ("package".equals(cmd)) {
8551 String[] newArgs;
8552 if (opti >= args.length) {
8553 pw.println("package: no package name specified");
8554 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 } else {
8556 dumpPackage = args[opti];
8557 opti++;
8558 newArgs = new String[args.length - opti];
8559 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8560 args.length - opti);
8561 args = newArgs;
8562 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008563 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008564 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8566 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008567 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008569 } else {
8570 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008571 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8572 pw.println("Bad activity command, or no activities match: " + cmd);
8573 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008574 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008575 }
8576 if (!more) {
8577 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008578 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008581
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008582 // No piece of data specified, dump everything.
8583 synchronized (this) {
8584 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008585 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 if (needSep) {
8587 pw.println(" ");
8588 }
8589 if (dumpAll) {
8590 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008591 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008592 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593 if (needSep) {
8594 pw.println(" ");
8595 }
8596 if (dumpAll) {
8597 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008598 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008599 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008600 if (needSep) {
8601 pw.println(" ");
8602 }
8603 if (dumpAll) {
8604 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008606 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008607 if (needSep) {
8608 pw.println(" ");
8609 }
8610 if (dumpAll) {
8611 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008612 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008613 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008614 if (needSep) {
8615 pw.println(" ");
8616 }
8617 if (dumpAll) {
8618 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008619 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008620 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008621 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008622 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008623 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008624
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008625 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008626 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008627 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8628 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008629 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8630 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008631 pw.println(" ");
8632 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008633 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8634 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008635 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008637 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008638 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008639 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008640 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008641 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008644 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008645 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008646 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008647 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8648 pw.println(" ");
8649 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008650 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008651 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008652 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008653 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008654 pw.println(" ");
8655 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008656 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008657 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008660 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008661 if (mMainStack.mPausingActivity != null) {
8662 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008663 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008664 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008665 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008666 if (dumpAll) {
8667 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8668 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008669 pw.println(" mDismissKeyguardOnNextActivity: "
8670 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008673 if (mRecentTasks.size() > 0) {
8674 pw.println();
8675 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008676
8677 final int N = mRecentTasks.size();
8678 for (int i=0; i<N; i++) {
8679 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008680 if (dumpPackage != null) {
8681 if (tr.realActivity == null ||
8682 !dumpPackage.equals(tr.realActivity)) {
8683 continue;
8684 }
8685 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008686 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8687 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008688 if (dumpAll) {
8689 mRecentTasks.get(i).dump(pw, " ");
8690 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008691 }
8692 }
8693
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008694 if (dumpAll) {
8695 pw.println(" ");
8696 pw.println(" mCurTask: " + mCurTask);
8697 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008698
8699 return true;
8700 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008701
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008702 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008703 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008704 boolean needSep = false;
8705 int numPers = 0;
8706
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008707 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8708
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008709 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8711 final int NA = procs.size();
8712 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008713 ProcessRecord r = procs.valueAt(ia);
8714 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8715 continue;
8716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717 if (!needSep) {
8718 pw.println(" All known processes:");
8719 needSep = true;
8720 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008721 pw.print(r.persistent ? " *PERS*" : " *APP*");
8722 pw.print(" UID "); pw.print(procs.keyAt(ia));
8723 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008724 r.dump(pw, " ");
8725 if (r.persistent) {
8726 numPers++;
8727 }
8728 }
8729 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008731
8732 if (mIsolatedProcesses.size() > 0) {
8733 if (needSep) pw.println(" ");
8734 needSep = true;
8735 pw.println(" Isolated process list (sorted by uid):");
8736 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8737 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8738 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8739 continue;
8740 }
8741 pw.println(String.format("%sIsolated #%2d: %s",
8742 " ", i, r.toString()));
8743 }
8744 }
8745
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008746 if (mLruProcesses.size() > 0) {
8747 if (needSep) pw.println(" ");
8748 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008749 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008750 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008751 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008752 needSep = true;
8753 }
8754
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008755 if (dumpAll) {
8756 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008757 boolean printed = false;
8758 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8759 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8760 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8761 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008762 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008763 if (!printed) {
8764 if (needSep) pw.println(" ");
8765 needSep = true;
8766 pw.println(" PID mappings:");
8767 printed = true;
8768 }
8769 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8770 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 }
8772 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008773 }
8774
8775 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 synchronized (mPidsSelfLocked) {
8777 boolean printed = false;
8778 for (int i=0; i<mForegroundProcesses.size(); i++) {
8779 ProcessRecord r = mPidsSelfLocked.get(
8780 mForegroundProcesses.valueAt(i).pid);
8781 if (dumpPackage != null && (r == null
8782 || !dumpPackage.equals(r.info.packageName))) {
8783 continue;
8784 }
8785 if (!printed) {
8786 if (needSep) pw.println(" ");
8787 needSep = true;
8788 pw.println(" Foreground Processes:");
8789 printed = true;
8790 }
8791 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8792 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008795 }
8796
8797 if (mPersistentStartingProcesses.size() > 0) {
8798 if (needSep) pw.println(" ");
8799 needSep = true;
8800 pw.println(" Persisent processes that are starting:");
8801 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008802 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008805 if (mRemovedProcesses.size() > 0) {
8806 if (needSep) pw.println(" ");
8807 needSep = true;
8808 pw.println(" Processes that are being removed:");
8809 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008810 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008811 }
8812
8813 if (mProcessesOnHold.size() > 0) {
8814 if (needSep) pw.println(" ");
8815 needSep = true;
8816 pw.println(" Processes that are on old until the system is ready:");
8817 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008818 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008821 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008822
8823 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008824 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008825 long now = SystemClock.uptimeMillis();
8826 for (Map.Entry<String, SparseArray<Long>> procs
8827 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008828 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008829 SparseArray<Long> uids = procs.getValue();
8830 final int N = uids.size();
8831 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008832 int puid = uids.keyAt(i);
8833 ProcessRecord r = mProcessNames.get(pname, puid);
8834 if (dumpPackage != null && (r == null
8835 || !dumpPackage.equals(r.info.packageName))) {
8836 continue;
8837 }
8838 if (!printed) {
8839 if (needSep) pw.println(" ");
8840 needSep = true;
8841 pw.println(" Time since processes crashed:");
8842 printed = true;
8843 }
8844 pw.print(" Process "); pw.print(pname);
8845 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008846 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008847 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8848 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008849 }
8850 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008853 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008854 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008855 for (Map.Entry<String, SparseArray<Long>> procs
8856 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008857 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008858 SparseArray<Long> uids = procs.getValue();
8859 final int N = uids.size();
8860 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008861 int puid = uids.keyAt(i);
8862 ProcessRecord r = mProcessNames.get(pname, puid);
8863 if (dumpPackage != null && (r == null
8864 || !dumpPackage.equals(r.info.packageName))) {
8865 continue;
8866 }
8867 if (!printed) {
8868 if (needSep) pw.println(" ");
8869 needSep = true;
8870 pw.println(" Bad processes:");
8871 }
8872 pw.print(" Bad process "); pw.print(pname);
8873 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008874 pw.print(": crashed at time ");
8875 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 }
8877 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008879
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008880 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008881 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008882 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008883 if (dumpAll) {
8884 StringBuilder sb = new StringBuilder(128);
8885 sb.append(" mPreviousProcessVisibleTime: ");
8886 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8887 pw.println(sb);
8888 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008889 if (mHeavyWeightProcess != null) {
8890 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8891 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008892 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008893 if (dumpAll) {
8894 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008895 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008896 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008897 for (Map.Entry<String, Integer> entry
8898 : mCompatModePackages.getPackages().entrySet()) {
8899 String pkg = entry.getKey();
8900 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008901 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8902 continue;
8903 }
8904 if (!printed) {
8905 pw.println(" mScreenCompatPackages:");
8906 printed = true;
8907 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008908 pw.print(" "); pw.print(pkg); pw.print(": ");
8909 pw.print(mode); pw.println();
8910 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008911 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008912 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008913 if (mSleeping || mWentToSleep || mLockScreenShown) {
8914 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8915 + " mLockScreenShown " + mLockScreenShown);
8916 }
8917 if (mShuttingDown) {
8918 pw.println(" mShuttingDown=" + mShuttingDown);
8919 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008920 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8921 || mOrigWaitForDebugger) {
8922 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8923 + " mDebugTransient=" + mDebugTransient
8924 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8925 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008926 if (mOpenGlTraceApp != null) {
8927 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8928 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008929 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8930 || mProfileFd != null) {
8931 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8932 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8933 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8934 + mAutoStopProfiler);
8935 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008936 if (mAlwaysFinishActivities || mController != null) {
8937 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8938 + " mController=" + mController);
8939 }
8940 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008942 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008943 + " mProcessesReady=" + mProcessesReady
8944 + " mSystemReady=" + mSystemReady);
8945 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 + " mBooted=" + mBooted
8947 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008948 pw.print(" mLastPowerCheckRealtime=");
8949 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8950 pw.println("");
8951 pw.print(" mLastPowerCheckUptime=");
8952 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8953 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008954 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8955 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008956 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008957 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8958 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008960
8961 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 }
8963
Dianne Hackborn287952c2010-09-22 22:34:31 -07008964 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008965 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008966 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008967 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008968 long now = SystemClock.uptimeMillis();
8969 for (int i=0; i<mProcessesToGc.size(); i++) {
8970 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008971 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8972 continue;
8973 }
8974 if (!printed) {
8975 if (needSep) pw.println(" ");
8976 needSep = true;
8977 pw.println(" Processes that are waiting to GC:");
8978 printed = true;
8979 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008980 pw.print(" Process "); pw.println(proc);
8981 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8982 pw.print(", last gced=");
8983 pw.print(now-proc.lastRequestedGc);
8984 pw.print(" ms ago, last lowMem=");
8985 pw.print(now-proc.lastLowMemory);
8986 pw.println(" ms ago");
8987
8988 }
8989 }
8990 return needSep;
8991 }
8992
8993 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8994 int opti, boolean dumpAll) {
8995 boolean needSep = false;
8996
8997 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008998 if (needSep) pw.println(" ");
8999 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009000 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009001 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009002 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009003 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9004 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9005 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9006 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9007 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009008 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009009 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009010 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009011 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009012 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009013 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009014
9015 if (needSep) pw.println(" ");
9016 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009017 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009018 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009019 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009020 needSep = true;
9021 }
9022
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009023 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009024
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009025 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009026 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009027 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009028 if (mHeavyWeightProcess != null) {
9029 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9030 }
9031
9032 return true;
9033 }
9034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 /**
9036 * There are three ways to call this:
9037 * - no service specified: dump all the services
9038 * - a flattened component name that matched an existing service was specified as the
9039 * first arg: dump that one service
9040 * - the first arg isn't the flattened component name of an existing service:
9041 * dump all services whose component contains the first arg as a substring
9042 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009043 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9044 int opti, boolean dumpAll) {
9045 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009047 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009048 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009049 try {
9050 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9051 for (UserInfo user : users) {
9052 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9053 services.add(r1);
9054 }
9055 }
9056 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057 }
9058 }
9059 } else {
9060 ComponentName componentName = name != null
9061 ? ComponentName.unflattenFromString(name) : null;
9062 int objectId = 0;
9063 if (componentName == null) {
9064 // Not a '/' separated full component name; maybe an object ID?
9065 try {
9066 objectId = Integer.parseInt(name, 16);
9067 name = null;
9068 componentName = null;
9069 } catch (RuntimeException e) {
9070 }
9071 }
9072
9073 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009074 try {
9075 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9076 for (UserInfo user : users) {
9077 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9078 if (componentName != null) {
9079 if (r1.name.equals(componentName)) {
9080 services.add(r1);
9081 }
9082 } else if (name != null) {
9083 if (r1.name.flattenToString().contains(name)) {
9084 services.add(r1);
9085 }
9086 } else if (System.identityHashCode(r1) == objectId) {
9087 services.add(r1);
9088 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009089 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009090 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009091 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 }
9093 }
9094 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009095
9096 if (services.size() <= 0) {
9097 return false;
9098 }
9099
9100 boolean needSep = false;
9101 for (int i=0; i<services.size(); i++) {
9102 if (needSep) {
9103 pw.println();
9104 }
9105 needSep = true;
9106 dumpService("", fd, pw, services.get(i), args, dumpAll);
9107 }
9108 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 }
9110
9111 /**
9112 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9113 * there is a thread associated with the service.
9114 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009115 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9116 final ServiceRecord r, String[] args, boolean dumpAll) {
9117 String innerPrefix = prefix + " ";
9118 synchronized (this) {
9119 pw.print(prefix); pw.print("SERVICE ");
9120 pw.print(r.shortName); pw.print(" ");
9121 pw.print(Integer.toHexString(System.identityHashCode(r)));
9122 pw.print(" pid=");
9123 if (r.app != null) pw.println(r.app.pid);
9124 else pw.println("(not running)");
9125 if (dumpAll) {
9126 r.dump(pw, innerPrefix);
9127 }
9128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009130 pw.print(prefix); pw.println(" Client:");
9131 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009133 TransferPipe tp = new TransferPipe();
9134 try {
9135 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9136 tp.setBufferPrefix(prefix + " ");
9137 tp.go(fd);
9138 } finally {
9139 tp.kill();
9140 }
9141 } catch (IOException e) {
9142 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009144 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145 }
9146 }
9147 }
9148
Marco Nelissen18cb2872011-11-15 11:19:53 -08009149 /**
9150 * There are three ways to call this:
9151 * - no provider specified: dump all the providers
9152 * - a flattened component name that matched an existing provider was specified as the
9153 * first arg: dump that one provider
9154 * - the first arg isn't the flattened component name of an existing provider:
9155 * dump all providers whose component contains the first arg as a substring
9156 */
9157 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9158 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009159 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009160 }
9161
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009162 static class ItemMatcher {
9163 ArrayList<ComponentName> components;
9164 ArrayList<String> strings;
9165 ArrayList<Integer> objects;
9166 boolean all;
9167
9168 ItemMatcher() {
9169 all = true;
9170 }
9171
9172 void build(String name) {
9173 ComponentName componentName = ComponentName.unflattenFromString(name);
9174 if (componentName != null) {
9175 if (components == null) {
9176 components = new ArrayList<ComponentName>();
9177 }
9178 components.add(componentName);
9179 all = false;
9180 } else {
9181 int objectId = 0;
9182 // Not a '/' separated full component name; maybe an object ID?
9183 try {
9184 objectId = Integer.parseInt(name, 16);
9185 if (objects == null) {
9186 objects = new ArrayList<Integer>();
9187 }
9188 objects.add(objectId);
9189 all = false;
9190 } catch (RuntimeException e) {
9191 // Not an integer; just do string match.
9192 if (strings == null) {
9193 strings = new ArrayList<String>();
9194 }
9195 strings.add(name);
9196 all = false;
9197 }
9198 }
9199 }
9200
9201 int build(String[] args, int opti) {
9202 for (; opti<args.length; opti++) {
9203 String name = args[opti];
9204 if ("--".equals(name)) {
9205 return opti+1;
9206 }
9207 build(name);
9208 }
9209 return opti;
9210 }
9211
9212 boolean match(Object object, ComponentName comp) {
9213 if (all) {
9214 return true;
9215 }
9216 if (components != null) {
9217 for (int i=0; i<components.size(); i++) {
9218 if (components.get(i).equals(comp)) {
9219 return true;
9220 }
9221 }
9222 }
9223 if (objects != null) {
9224 for (int i=0; i<objects.size(); i++) {
9225 if (System.identityHashCode(object) == objects.get(i)) {
9226 return true;
9227 }
9228 }
9229 }
9230 if (strings != null) {
9231 String flat = comp.flattenToString();
9232 for (int i=0; i<strings.size(); i++) {
9233 if (flat.contains(strings.get(i))) {
9234 return true;
9235 }
9236 }
9237 }
9238 return false;
9239 }
9240 }
9241
Dianne Hackborn625ac272010-09-17 18:29:22 -07009242 /**
9243 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009244 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009245 * - the cmd arg isn't the flattened component name of an existing activity:
9246 * dump all activity whose component contains the cmd as a substring
9247 * - A hex number of the ActivityRecord object instance.
9248 */
9249 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9250 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009251 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009252
9253 if ("all".equals(name)) {
9254 synchronized (this) {
9255 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009256 activities.add(r1);
9257 }
9258 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009259 } else if ("top".equals(name)) {
9260 synchronized (this) {
9261 final int N = mMainStack.mHistory.size();
9262 if (N > 0) {
9263 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9264 }
9265 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009266 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009267 ItemMatcher matcher = new ItemMatcher();
9268 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009269
9270 synchronized (this) {
9271 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009272 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009273 activities.add(r1);
9274 }
9275 }
9276 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009277 }
9278
9279 if (activities.size() <= 0) {
9280 return false;
9281 }
9282
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009283 String[] newArgs = new String[args.length - opti];
9284 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9285
Dianne Hackborn30d71892010-12-11 10:37:55 -08009286 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009287 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009288 for (int i=activities.size()-1; i>=0; i--) {
9289 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009290 if (needSep) {
9291 pw.println();
9292 }
9293 needSep = true;
9294 synchronized (this) {
9295 if (lastTask != r.task) {
9296 lastTask = r.task;
9297 pw.print("TASK "); pw.print(lastTask.affinity);
9298 pw.print(" id="); pw.println(lastTask.taskId);
9299 if (dumpAll) {
9300 lastTask.dump(pw, " ");
9301 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009302 }
9303 }
9304 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009305 }
9306 return true;
9307 }
9308
9309 /**
9310 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9311 * there is a thread associated with the activity.
9312 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009313 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009314 final ActivityRecord r, String[] args, boolean dumpAll) {
9315 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009316 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009317 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9318 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9319 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009320 if (r.app != null) pw.println(r.app.pid);
9321 else pw.println("(not running)");
9322 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009323 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009324 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009325 }
9326 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009327 // flush anything that is already in the PrintWriter since the thread is going
9328 // to write to the file descriptor directly
9329 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009330 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009331 TransferPipe tp = new TransferPipe();
9332 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009333 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9334 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009335 tp.go(fd);
9336 } finally {
9337 tp.kill();
9338 }
9339 } catch (IOException e) {
9340 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009341 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009342 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009343 }
9344 }
9345 }
9346
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009347 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009348 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009349 boolean needSep = false;
9350
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009351 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009352 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009354 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009355 Iterator it = mRegisteredReceivers.values().iterator();
9356 while (it.hasNext()) {
9357 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009358 if (dumpPackage != null && (r.app == null ||
9359 !dumpPackage.equals(r.app.info.packageName))) {
9360 continue;
9361 }
9362 if (!printed) {
9363 pw.println(" Registered Receivers:");
9364 needSep = true;
9365 printed = true;
9366 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009367 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 r.dump(pw, " ");
9369 }
9370 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009371
9372 if (mReceiverResolver.dump(pw, needSep ?
9373 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9374 " ", dumpPackage, false)) {
9375 needSep = true;
9376 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009378
9379 for (BroadcastQueue q : mBroadcastQueues) {
9380 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009383 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009384
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009385 if (mStickyBroadcasts != null && dumpPackage == null) {
9386 if (needSep) {
9387 pw.println();
9388 }
9389 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009390 pw.println(" Sticky broadcasts:");
9391 StringBuilder sb = new StringBuilder(128);
9392 for (Map.Entry<String, ArrayList<Intent>> ent
9393 : mStickyBroadcasts.entrySet()) {
9394 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009395 if (dumpAll) {
9396 pw.println(":");
9397 ArrayList<Intent> intents = ent.getValue();
9398 final int N = intents.size();
9399 for (int i=0; i<N; i++) {
9400 sb.setLength(0);
9401 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009402 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009403 pw.println(sb.toString());
9404 Bundle bundle = intents.get(i).getExtras();
9405 if (bundle != null) {
9406 pw.print(" ");
9407 pw.println(bundle.toString());
9408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009410 } else {
9411 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 }
9413 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009414 needSep = true;
9415 }
9416
9417 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009418 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009419 for (BroadcastQueue queue : mBroadcastQueues) {
9420 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9421 + queue.mBroadcastsScheduled);
9422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 pw.println(" mHandler:");
9424 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009425 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009426 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009427
9428 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009429 }
9430
Marco Nelissen18cb2872011-11-15 11:19:53 -08009431 /**
9432 * Prints a list of ServiceRecords (dumpsys activity services)
9433 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009434 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009435 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009436 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009437
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009438 ItemMatcher matcher = new ItemMatcher();
9439 matcher.build(args, opti);
9440
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009441 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009442 try {
9443 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9444 for (UserInfo user : users) {
9445 if (mServiceMap.getAllServices(user.id).size() > 0) {
9446 boolean printed = false;
9447 long nowReal = SystemClock.elapsedRealtime();
9448 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9449 user.id).iterator();
9450 needSep = false;
9451 while (it.hasNext()) {
9452 ServiceRecord r = it.next();
9453 if (!matcher.match(r, r.name)) {
9454 continue;
9455 }
9456 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9457 continue;
9458 }
9459 if (!printed) {
9460 pw.println(" Active services:");
9461 printed = true;
9462 }
9463 if (needSep) {
9464 pw.println();
9465 }
9466 pw.print(" * ");
9467 pw.println(r);
9468 if (dumpAll) {
9469 r.dump(pw, " ");
9470 needSep = true;
9471 } else {
9472 pw.print(" app=");
9473 pw.println(r.app);
9474 pw.print(" created=");
9475 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9476 pw.print(" started=");
9477 pw.print(r.startRequested);
9478 pw.print(" connections=");
9479 pw.println(r.connections.size());
9480 if (r.connections.size() > 0) {
9481 pw.println(" Connections:");
9482 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9483 for (int i = 0; i < clist.size(); i++) {
9484 ConnectionRecord conn = clist.get(i);
9485 pw.print(" ");
9486 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009487 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009488 pw.print(" -> ");
9489 ProcessRecord proc = conn.binding.client;
9490 pw.println(proc != null ? proc.toShortString() : "null");
9491 }
9492 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009493 }
9494 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009495 if (dumpClient && r.app != null && r.app.thread != null) {
9496 pw.println(" Client:");
9497 pw.flush();
9498 try {
9499 TransferPipe tp = new TransferPipe();
9500 try {
9501 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9502 r, args);
9503 tp.setBufferPrefix(" ");
9504 // Short timeout, since blocking here can
9505 // deadlock with the application.
9506 tp.go(fd, 2000);
9507 } finally {
9508 tp.kill();
9509 }
9510 } catch (IOException e) {
9511 pw.println(" Failure while dumping the service: " + e);
9512 } catch (RemoteException e) {
9513 pw.println(" Got a RemoteException while dumping the service");
9514 }
9515 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009516 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009517 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009518 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009520 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009521 } catch (RemoteException re) {
9522
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009525 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009526 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009527 for (int i=0; i<mPendingServices.size(); i++) {
9528 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009529 if (!matcher.match(r, r.name)) {
9530 continue;
9531 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009532 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9533 continue;
9534 }
9535 if (!printed) {
9536 if (needSep) pw.println(" ");
9537 needSep = true;
9538 pw.println(" Pending services:");
9539 printed = true;
9540 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009541 pw.print(" * Pending "); pw.println(r);
9542 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009544 needSep = true;
9545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009547 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009548 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009549 for (int i=0; i<mRestartingServices.size(); i++) {
9550 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009551 if (!matcher.match(r, r.name)) {
9552 continue;
9553 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009554 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9555 continue;
9556 }
9557 if (!printed) {
9558 if (needSep) pw.println(" ");
9559 needSep = true;
9560 pw.println(" Restarting services:");
9561 printed = true;
9562 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009563 pw.print(" * Restarting "); pw.println(r);
9564 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009566 needSep = true;
9567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009568
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009569 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009570 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009571 for (int i=0; i<mStoppingServices.size(); i++) {
9572 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009573 if (!matcher.match(r, r.name)) {
9574 continue;
9575 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009576 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9577 continue;
9578 }
9579 if (!printed) {
9580 if (needSep) pw.println(" ");
9581 needSep = true;
9582 pw.println(" Stopping services:");
9583 printed = true;
9584 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009585 pw.print(" * Stopping "); pw.println(r);
9586 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009588 needSep = true;
9589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009591 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009593 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009594 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009595 = mServiceConnections.values().iterator();
9596 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009597 ArrayList<ConnectionRecord> r = it.next();
9598 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009599 ConnectionRecord cr = r.get(i);
9600 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9601 continue;
9602 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009603 if (dumpPackage != null && (cr.binding.client == null
9604 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9605 continue;
9606 }
9607 if (!printed) {
9608 if (needSep) pw.println(" ");
9609 needSep = true;
9610 pw.println(" Connection bindings to services:");
9611 printed = true;
9612 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009613 pw.print(" * "); pw.println(cr);
9614 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009617 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009618 }
9619 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009620
9621 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009622 }
9623
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009624 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009625 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009626 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009627
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009628 ItemMatcher matcher = new ItemMatcher();
9629 matcher.build(args, opti);
9630
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009631 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009632
9633 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009634
9635 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009636 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009637 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009638 ContentProviderRecord r = mLaunchingProviders.get(i);
9639 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9640 continue;
9641 }
9642 if (!printed) {
9643 if (needSep) pw.println(" ");
9644 needSep = true;
9645 pw.println(" Launching content providers:");
9646 printed = true;
9647 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009648 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009649 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009650 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009651 }
9652
9653 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009654 if (needSep) pw.println();
9655 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009656 pw.println("Granted Uri Permissions:");
9657 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9658 int uid = mGrantedUriPermissions.keyAt(i);
9659 HashMap<Uri, UriPermission> perms
9660 = mGrantedUriPermissions.valueAt(i);
9661 pw.print(" * UID "); pw.print(uid);
9662 pw.println(" holds:");
9663 for (UriPermission perm : perms.values()) {
9664 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009665 if (dumpAll) {
9666 perm.dump(pw, " ");
9667 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009668 }
9669 }
9670 needSep = true;
9671 }
9672
9673 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009674 }
9675
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009676 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009677 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009678 boolean needSep = false;
9679
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009680 if (mIntentSenderRecords.size() > 0) {
9681 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009682 Iterator<WeakReference<PendingIntentRecord>> it
9683 = mIntentSenderRecords.values().iterator();
9684 while (it.hasNext()) {
9685 WeakReference<PendingIntentRecord> ref = it.next();
9686 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009687 if (dumpPackage != null && (rec == null
9688 || !dumpPackage.equals(rec.key.packageName))) {
9689 continue;
9690 }
9691 if (!printed) {
9692 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9693 printed = true;
9694 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009695 needSep = true;
9696 if (rec != null) {
9697 pw.print(" * "); pw.println(rec);
9698 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009701 } else {
9702 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009703 }
9704 }
9705 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009706
9707 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009708 }
9709
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009710 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009711 String prefix, String label, boolean complete, boolean brief, boolean client,
9712 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009713 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009714 boolean needNL = false;
9715 final String innerPrefix = prefix + " ";
9716 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009717 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009718 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009719 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9720 continue;
9721 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009722 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009723 if (needNL) {
9724 pw.println(" ");
9725 needNL = false;
9726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727 if (lastTask != r.task) {
9728 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009729 pw.print(prefix);
9730 pw.print(full ? "* " : " ");
9731 pw.println(lastTask);
9732 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009733 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009734 } else if (complete) {
9735 // Complete + brief == give a summary. Isn't that obvious?!?
9736 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009737 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009738 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009739 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009741 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009742 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9743 pw.print(" #"); pw.print(i); pw.print(": ");
9744 pw.println(r);
9745 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009746 r.dump(pw, innerPrefix);
9747 } else if (complete) {
9748 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009749 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009750 if (r.app != null) {
9751 pw.print(innerPrefix); pw.println(r.app);
9752 }
9753 }
9754 if (client && r.app != null && r.app.thread != null) {
9755 // flush anything that is already in the PrintWriter since the thread is going
9756 // to write to the file descriptor directly
9757 pw.flush();
9758 try {
9759 TransferPipe tp = new TransferPipe();
9760 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009761 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9762 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009763 // Short timeout, since blocking here can
9764 // deadlock with the application.
9765 tp.go(fd, 2000);
9766 } finally {
9767 tp.kill();
9768 }
9769 } catch (IOException e) {
9770 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9771 } catch (RemoteException e) {
9772 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9773 }
9774 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009776 }
9777 }
9778
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009779 private static String buildOomTag(String prefix, String space, int val, int base) {
9780 if (val == base) {
9781 if (space == null) return prefix;
9782 return prefix + " ";
9783 }
9784 return prefix + "+" + Integer.toString(val-base);
9785 }
9786
9787 private static final int dumpProcessList(PrintWriter pw,
9788 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009789 String prefix, String normalLabel, String persistentLabel,
9790 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009791 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009792 final int N = list.size()-1;
9793 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009794 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009795 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9796 continue;
9797 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009798 pw.println(String.format("%s%s #%2d: %s",
9799 prefix, (r.persistent ? persistentLabel : normalLabel),
9800 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009801 if (r.persistent) {
9802 numPers++;
9803 }
9804 }
9805 return numPers;
9806 }
9807
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009808 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009809 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009810 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009811 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009812
Dianne Hackborn905577f2011-09-07 18:31:28 -07009813 ArrayList<Pair<ProcessRecord, Integer>> list
9814 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9815 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009816 ProcessRecord r = origList.get(i);
9817 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9818 continue;
9819 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009820 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9821 }
9822
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009823 if (list.size() <= 0) {
9824 return false;
9825 }
9826
Dianne Hackborn905577f2011-09-07 18:31:28 -07009827 Comparator<Pair<ProcessRecord, Integer>> comparator
9828 = new Comparator<Pair<ProcessRecord, Integer>>() {
9829 @Override
9830 public int compare(Pair<ProcessRecord, Integer> object1,
9831 Pair<ProcessRecord, Integer> object2) {
9832 if (object1.first.setAdj != object2.first.setAdj) {
9833 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9834 }
9835 if (object1.second.intValue() != object2.second.intValue()) {
9836 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9837 }
9838 return 0;
9839 }
9840 };
9841
9842 Collections.sort(list, comparator);
9843
Dianne Hackborn287952c2010-09-22 22:34:31 -07009844 final long curRealtime = SystemClock.elapsedRealtime();
9845 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9846 final long curUptime = SystemClock.uptimeMillis();
9847 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9848
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009849 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009850 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009851 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009852 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009853 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009854 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9855 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009856 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9857 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009858 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9859 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009860 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9861 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009862 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009863 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009864 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9865 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9866 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9867 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9868 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9869 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9870 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9871 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009872 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9873 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009874 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9875 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009876 } else {
9877 oomAdj = Integer.toString(r.setAdj);
9878 }
9879 String schedGroup;
9880 switch (r.setSchedGroup) {
9881 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9882 schedGroup = "B";
9883 break;
9884 case Process.THREAD_GROUP_DEFAULT:
9885 schedGroup = "F";
9886 break;
9887 default:
9888 schedGroup = Integer.toString(r.setSchedGroup);
9889 break;
9890 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009891 String foreground;
9892 if (r.foregroundActivities) {
9893 foreground = "A";
9894 } else if (r.foregroundServices) {
9895 foreground = "S";
9896 } else {
9897 foreground = " ";
9898 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009899 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009900 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009901 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9902 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009903 if (r.adjSource != null || r.adjTarget != null) {
9904 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009905 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009906 if (r.adjTarget instanceof ComponentName) {
9907 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9908 } else if (r.adjTarget != null) {
9909 pw.print(r.adjTarget.toString());
9910 } else {
9911 pw.print("{null}");
9912 }
9913 pw.print("<=");
9914 if (r.adjSource instanceof ProcessRecord) {
9915 pw.print("Proc{");
9916 pw.print(((ProcessRecord)r.adjSource).toShortString());
9917 pw.println("}");
9918 } else if (r.adjSource != null) {
9919 pw.println(r.adjSource.toString());
9920 } else {
9921 pw.println("{null}");
9922 }
9923 }
9924 if (inclDetails) {
9925 pw.print(prefix);
9926 pw.print(" ");
9927 pw.print("oom: max="); pw.print(r.maxAdj);
9928 pw.print(" hidden="); pw.print(r.hiddenAdj);
9929 pw.print(" curRaw="); pw.print(r.curRawAdj);
9930 pw.print(" setRaw="); pw.print(r.setRawAdj);
9931 pw.print(" cur="); pw.print(r.curAdj);
9932 pw.print(" set="); pw.println(r.setAdj);
9933 pw.print(prefix);
9934 pw.print(" ");
9935 pw.print("keeping="); pw.print(r.keeping);
9936 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009937 pw.print(" empty="); pw.print(r.empty);
9938 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009939
9940 if (!r.keeping) {
9941 if (r.lastWakeTime != 0) {
9942 long wtime;
9943 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9944 synchronized (stats) {
9945 wtime = stats.getProcessWakeTime(r.info.uid,
9946 r.pid, curRealtime);
9947 }
9948 long timeUsed = wtime - r.lastWakeTime;
9949 pw.print(prefix);
9950 pw.print(" ");
9951 pw.print("keep awake over ");
9952 TimeUtils.formatDuration(realtimeSince, pw);
9953 pw.print(" used ");
9954 TimeUtils.formatDuration(timeUsed, pw);
9955 pw.print(" (");
9956 pw.print((timeUsed*100)/realtimeSince);
9957 pw.println("%)");
9958 }
9959 if (r.lastCpuTime != 0) {
9960 long timeUsed = r.curCpuTime - r.lastCpuTime;
9961 pw.print(prefix);
9962 pw.print(" ");
9963 pw.print("run cpu over ");
9964 TimeUtils.formatDuration(uptimeSince, pw);
9965 pw.print(" used ");
9966 TimeUtils.formatDuration(timeUsed, pw);
9967 pw.print(" (");
9968 pw.print((timeUsed*100)/uptimeSince);
9969 pw.println("%)");
9970 }
9971 }
9972 }
9973 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009974 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009975 }
9976
Dianne Hackbornb437e092011-08-05 17:50:29 -07009977 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009978 ArrayList<ProcessRecord> procs;
9979 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009980 if (args != null && args.length > start
9981 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009982 procs = new ArrayList<ProcessRecord>();
9983 int pid = -1;
9984 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009985 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009986 } catch (NumberFormatException e) {
9987
9988 }
9989 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9990 ProcessRecord proc = mLruProcesses.get(i);
9991 if (proc.pid == pid) {
9992 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009993 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009994 procs.add(proc);
9995 }
9996 }
9997 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009998 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009999 return null;
10000 }
10001 } else {
10002 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10003 }
10004 }
10005 return procs;
10006 }
10007
10008 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10009 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010010 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010011 if (procs == null) {
10012 return;
10013 }
10014
10015 long uptime = SystemClock.uptimeMillis();
10016 long realtime = SystemClock.elapsedRealtime();
10017 pw.println("Applications Graphics Acceleration Info:");
10018 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10019
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010020 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10021 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010022 if (r.thread != null) {
10023 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10024 pw.flush();
10025 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010026 TransferPipe tp = new TransferPipe();
10027 try {
10028 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10029 tp.go(fd);
10030 } finally {
10031 tp.kill();
10032 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010033 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010034 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010035 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010036 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010037 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010038 pw.flush();
10039 }
10040 }
10041 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010042 }
10043
Jeff Brown6754ba22011-12-14 20:20:01 -080010044 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10045 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10046 if (procs == null) {
10047 return;
10048 }
10049
10050 pw.println("Applications Database Info:");
10051
10052 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10053 ProcessRecord r = procs.get(i);
10054 if (r.thread != null) {
10055 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10056 pw.flush();
10057 try {
10058 TransferPipe tp = new TransferPipe();
10059 try {
10060 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10061 tp.go(fd);
10062 } finally {
10063 tp.kill();
10064 }
10065 } catch (IOException e) {
10066 pw.println("Failure while dumping the app: " + r);
10067 pw.flush();
10068 } catch (RemoteException e) {
10069 pw.println("Got a RemoteException while dumping the app " + r);
10070 pw.flush();
10071 }
10072 }
10073 }
10074 }
10075
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010076 final static class MemItem {
10077 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010078 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010079 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010080 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010081 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010082
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010083 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010084 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010085 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010086 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010087 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010088 }
10089 }
10090
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010091 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010092 boolean sort) {
10093 if (sort) {
10094 Collections.sort(items, new Comparator<MemItem>() {
10095 @Override
10096 public int compare(MemItem lhs, MemItem rhs) {
10097 if (lhs.pss < rhs.pss) {
10098 return 1;
10099 } else if (lhs.pss > rhs.pss) {
10100 return -1;
10101 }
10102 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010103 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010104 });
10105 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010106
10107 for (int i=0; i<items.size(); i++) {
10108 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010109 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010110 if (mi.subitems != null) {
10111 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10112 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010113 }
10114 }
10115
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010116 // These are in KB.
10117 static final long[] DUMP_MEM_BUCKETS = new long[] {
10118 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10119 120*1024, 160*1024, 200*1024,
10120 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10121 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10122 };
10123
Dianne Hackborn672342c2011-11-29 11:29:02 -080010124 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10125 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010126 int start = label.lastIndexOf('.');
10127 if (start >= 0) start++;
10128 else start = 0;
10129 int end = label.length();
10130 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10131 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10132 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10133 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010134 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010135 out.append(label, start, end);
10136 return;
10137 }
10138 }
10139 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010140 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010141 out.append(label, start, end);
10142 }
10143
10144 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10145 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10146 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10147 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10148 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10149 };
10150 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10151 "System", "Persistent", "Foreground",
10152 "Visible", "Perceptible", "Heavy Weight",
10153 "Backup", "A Services", "Home", "Previous",
10154 "B Services", "Background"
10155 };
10156
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010157 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010158 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010159 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010160 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010161 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010162
10163 int opti = 0;
10164 while (opti < args.length) {
10165 String opt = args[opti];
10166 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10167 break;
10168 }
10169 opti++;
10170 if ("-a".equals(opt)) {
10171 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010172 } else if ("--oom".equals(opt)) {
10173 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010174 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010175 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010176 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010177 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010178 pw.println("If [process] is specified it can be the name or ");
10179 pw.println("pid of a specific process to dump.");
10180 return;
10181 } else {
10182 pw.println("Unknown argument: " + opt + "; use -h for help");
10183 }
10184 }
10185
10186 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010187 if (procs == null) {
10188 return;
10189 }
10190
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010191 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010192 long uptime = SystemClock.uptimeMillis();
10193 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010194
10195 if (procs.size() == 1 || isCheckinRequest) {
10196 dumpAll = true;
10197 }
10198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010199 if (isCheckinRequest) {
10200 // short checkin version
10201 pw.println(uptime + "," + realtime);
10202 pw.flush();
10203 } else {
10204 pw.println("Applications Memory Usage (kB):");
10205 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10206 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010207
Dianne Hackbornb437e092011-08-05 17:50:29 -070010208 String[] innerArgs = new String[args.length-opti];
10209 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10210
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010211 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10212 long nativePss=0, dalvikPss=0, otherPss=0;
10213 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10214
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010215 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10216 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10217 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010218
10219 long totalPss = 0;
10220
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010221 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10222 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010223 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010224 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010225 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10226 pw.flush();
10227 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010228 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010229 if (dumpAll) {
10230 try {
10231 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10232 } catch (RemoteException e) {
10233 if (!isCheckinRequest) {
10234 pw.println("Got RemoteException!");
10235 pw.flush();
10236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010237 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010238 } else {
10239 mi = new Debug.MemoryInfo();
10240 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010241 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010242
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010243 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010244 long myTotalPss = mi.getTotalPss();
10245 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010246 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010247 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010248 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010249
10250 nativePss += mi.nativePss;
10251 dalvikPss += mi.dalvikPss;
10252 otherPss += mi.otherPss;
10253 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10254 long mem = mi.getOtherPss(j);
10255 miscPss[j] += mem;
10256 otherPss -= mem;
10257 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010258
10259 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010260 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10261 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010262 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010263 if (oomProcs[oomIndex] == null) {
10264 oomProcs[oomIndex] = new ArrayList<MemItem>();
10265 }
10266 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010267 break;
10268 }
10269 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010271 }
10272 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010273
10274 if (!isCheckinRequest && procs.size() > 1) {
10275 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10276
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010277 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10278 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10279 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010280 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010281 String label = Debug.MemoryInfo.getOtherLabel(j);
10282 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010283 }
10284
Dianne Hackbornb437e092011-08-05 17:50:29 -070010285 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10286 for (int j=0; j<oomPss.length; j++) {
10287 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010288 String label = DUMP_MEM_OOM_LABEL[j];
10289 MemItem item = new MemItem(label, label, oomPss[j],
10290 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010291 item.subitems = oomProcs[j];
10292 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010293 }
10294 }
10295
Dianne Hackborn672342c2011-11-29 11:29:02 -080010296 if (outTag != null || outStack != null) {
10297 if (outTag != null) {
10298 appendMemBucket(outTag, totalPss, "total", false);
10299 }
10300 if (outStack != null) {
10301 appendMemBucket(outStack, totalPss, "total", true);
10302 }
10303 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010304 for (int i=0; i<oomMems.size(); i++) {
10305 MemItem miCat = oomMems.get(i);
10306 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10307 continue;
10308 }
10309 if (miCat.id < ProcessList.SERVICE_ADJ
10310 || miCat.id == ProcessList.HOME_APP_ADJ
10311 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010312 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10313 outTag.append(" / ");
10314 }
10315 if (outStack != null) {
10316 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10317 if (firstLine) {
10318 outStack.append(":");
10319 firstLine = false;
10320 }
10321 outStack.append("\n\t at ");
10322 } else {
10323 outStack.append("$");
10324 }
10325 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010326 for (int j=0; j<miCat.subitems.size(); j++) {
10327 MemItem mi = miCat.subitems.get(j);
10328 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010329 if (outTag != null) {
10330 outTag.append(" ");
10331 }
10332 if (outStack != null) {
10333 outStack.append("$");
10334 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010335 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010336 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10337 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10338 }
10339 if (outStack != null) {
10340 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10341 }
10342 }
10343 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10344 outStack.append("(");
10345 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10346 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10347 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10348 outStack.append(":");
10349 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10350 }
10351 }
10352 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010353 }
10354 }
10355 }
10356 }
10357
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010358 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010359 pw.println();
10360 pw.println("Total PSS by process:");
10361 dumpMemItems(pw, " ", procMems, true);
10362 pw.println();
10363 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010364 pw.println("Total PSS by OOM adjustment:");
10365 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010366 if (!oomOnly) {
10367 PrintWriter out = categoryPw != null ? categoryPw : pw;
10368 out.println();
10369 out.println("Total PSS by category:");
10370 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010371 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010372 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010373 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010374 final int[] SINGLE_LONG_FORMAT = new int[] {
10375 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10376 };
10377 long[] longOut = new long[1];
10378 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10379 SINGLE_LONG_FORMAT, null, longOut, null);
10380 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10381 longOut[0] = 0;
10382 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10383 SINGLE_LONG_FORMAT, null, longOut, null);
10384 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10385 longOut[0] = 0;
10386 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10387 SINGLE_LONG_FORMAT, null, longOut, null);
10388 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10389 longOut[0] = 0;
10390 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10391 SINGLE_LONG_FORMAT, null, longOut, null);
10392 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10393 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10394 pw.print(shared); pw.println(" kB");
10395 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10396 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010398 }
10399
10400 /**
10401 * Searches array of arguments for the specified string
10402 * @param args array of argument strings
10403 * @param value value to search for
10404 * @return true if the value is contained in the array
10405 */
10406 private static boolean scanArgs(String[] args, String value) {
10407 if (args != null) {
10408 for (String arg : args) {
10409 if (value.equals(arg)) {
10410 return true;
10411 }
10412 }
10413 }
10414 return false;
10415 }
10416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010417 private final void killServicesLocked(ProcessRecord app,
10418 boolean allowRestart) {
10419 // Report disconnected services.
10420 if (false) {
10421 // XXX we are letting the client link to the service for
10422 // death notifications.
10423 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010424 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010425 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010426 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010427 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010428 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429 = r.connections.values().iterator();
10430 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010431 ArrayList<ConnectionRecord> cl = jt.next();
10432 for (int i=0; i<cl.size(); i++) {
10433 ConnectionRecord c = cl.get(i);
10434 if (c.binding.client != app) {
10435 try {
10436 //c.conn.connected(r.className, null);
10437 } catch (Exception e) {
10438 // todo: this should be asynchronous!
10439 Slog.w(TAG, "Exception thrown disconnected servce "
10440 + r.shortName
10441 + " from app " + app.processName, e);
10442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010443 }
10444 }
10445 }
10446 }
10447 }
10448 }
10449 }
10450
10451 // Clean up any connections this application has to other services.
10452 if (app.connections.size() > 0) {
10453 Iterator<ConnectionRecord> it = app.connections.iterator();
10454 while (it.hasNext()) {
10455 ConnectionRecord r = it.next();
10456 removeConnectionLocked(r, app, null);
10457 }
10458 }
10459 app.connections.clear();
10460
10461 if (app.services.size() != 0) {
10462 // Any services running in the application need to be placed
10463 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010464 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010465 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010466 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010467 synchronized (sr.stats.getBatteryStats()) {
10468 sr.stats.stopLaunchedLocked();
10469 }
10470 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010471 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010473 if (mStoppingServices.remove(sr)) {
10474 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10475 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010476
10477 boolean hasClients = sr.bindings.size() > 0;
10478 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010479 Iterator<IntentBindRecord> bindings
10480 = sr.bindings.values().iterator();
10481 while (bindings.hasNext()) {
10482 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010483 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 + ": shouldUnbind=" + b.hasBound);
10485 b.binder = null;
10486 b.requested = b.received = b.hasBound = false;
10487 }
10488 }
10489
Dianne Hackborn070783f2010-12-29 16:46:28 -080010490 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10491 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010492 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010493 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010494 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010495 sr.crashCount, sr.shortName, app.pid);
10496 bringDownServiceLocked(sr, true);
10497 } else if (!allowRestart) {
10498 bringDownServiceLocked(sr, true);
10499 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010500 boolean canceled = scheduleServiceRestartLocked(sr, true);
10501
10502 // Should the service remain running? Note that in the
10503 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010504 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010505 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10506 if (sr.pendingStarts.size() == 0) {
10507 sr.startRequested = false;
10508 if (!hasClients) {
10509 // Whoops, no reason to restart!
10510 bringDownServiceLocked(sr, true);
10511 }
10512 }
10513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 }
10515 }
10516
10517 if (!allowRestart) {
10518 app.services.clear();
10519 }
10520 }
10521
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010522 // Make sure we have no more records on the stopping list.
10523 int i = mStoppingServices.size();
10524 while (i > 0) {
10525 i--;
10526 ServiceRecord sr = mStoppingServices.get(i);
10527 if (sr.app == app) {
10528 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010529 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010530 }
10531 }
10532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 app.executingServices.clear();
10534 }
10535
10536 private final void removeDyingProviderLocked(ProcessRecord proc,
10537 ContentProviderRecord cpr) {
10538 synchronized (cpr) {
10539 cpr.launchingApp = null;
10540 cpr.notifyAll();
10541 }
10542
Amith Yamasani742a6712011-05-04 14:49:28 -070010543 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 String names[] = cpr.info.authority.split(";");
10545 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010546 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010547 }
10548
10549 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10550 while (cit.hasNext()) {
10551 ProcessRecord capp = cit.next();
10552 if (!capp.persistent && capp.thread != null
10553 && capp.pid != 0
10554 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010555 Slog.i(TAG, "Kill " + capp.processName
10556 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010557 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010558 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010559 capp.processName, capp.setAdj, "dying provider "
10560 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010561 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 }
10563 }
10564
10565 mLaunchingProviders.remove(cpr);
10566 }
10567
10568 /**
10569 * Main code for cleaning up a process when it has gone away. This is
10570 * called both as a result of the process dying, or directly when stopping
10571 * a process when running in single process mode.
10572 */
10573 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010574 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010575 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010576 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 }
10578
Dianne Hackborn36124872009-10-08 16:22:03 -070010579 mProcessesToGc.remove(app);
10580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 // Dismiss any open dialogs.
10582 if (app.crashDialog != null) {
10583 app.crashDialog.dismiss();
10584 app.crashDialog = null;
10585 }
10586 if (app.anrDialog != null) {
10587 app.anrDialog.dismiss();
10588 app.anrDialog = null;
10589 }
10590 if (app.waitDialog != null) {
10591 app.waitDialog.dismiss();
10592 app.waitDialog = null;
10593 }
10594
10595 app.crashing = false;
10596 app.notResponding = false;
10597
10598 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010599 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 app.thread = null;
10601 app.forcingToForeground = null;
10602 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010603 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010604 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010605 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010606
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010607 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608
10609 boolean restart = false;
10610
10611 int NL = mLaunchingProviders.size();
10612
10613 // Remove published content providers.
10614 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010615 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010617 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010619 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010620
10621 // See if someone is waiting for this provider... in which
10622 // case we don't remove it, but just let it restart.
10623 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010624 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 for (; i<NL; i++) {
10626 if (mLaunchingProviders.get(i) == cpr) {
10627 restart = true;
10628 break;
10629 }
10630 }
10631 } else {
10632 i = NL;
10633 }
10634
10635 if (i >= NL) {
10636 removeDyingProviderLocked(app, cpr);
10637 NL = mLaunchingProviders.size();
10638 }
10639 }
10640 app.pubProviders.clear();
10641 }
10642
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010643 // Take care of any launching providers waiting for this process.
10644 if (checkAppInLaunchingProvidersLocked(app, false)) {
10645 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 // Unregister from connected content providers.
10649 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010650 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010651 while (it.hasNext()) {
10652 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10653 cpr.clients.remove(app);
10654 }
10655 app.conProviders.clear();
10656 }
10657
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010658 // At this point there may be remaining entries in mLaunchingProviders
10659 // where we were the only one waiting, so they are no longer of use.
10660 // Look for these and clean up if found.
10661 // XXX Commented out for now. Trying to figure out a way to reproduce
10662 // the actual situation to identify what is actually going on.
10663 if (false) {
10664 for (int i=0; i<NL; i++) {
10665 ContentProviderRecord cpr = (ContentProviderRecord)
10666 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010667 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010668 synchronized (cpr) {
10669 cpr.launchingApp = null;
10670 cpr.notifyAll();
10671 }
10672 }
10673 }
10674 }
10675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 skipCurrentReceiverLocked(app);
10677
10678 // Unregister any receivers.
10679 if (app.receivers.size() > 0) {
10680 Iterator<ReceiverList> it = app.receivers.iterator();
10681 while (it.hasNext()) {
10682 removeReceiverLocked(it.next());
10683 }
10684 app.receivers.clear();
10685 }
10686
Christopher Tate181fafa2009-05-14 11:12:14 -070010687 // If the app is undergoing backup, tell the backup manager about it
10688 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010689 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010690 try {
10691 IBackupManager bm = IBackupManager.Stub.asInterface(
10692 ServiceManager.getService(Context.BACKUP_SERVICE));
10693 bm.agentDisconnected(app.info.packageName);
10694 } catch (RemoteException e) {
10695 // can't happen; backup manager is local
10696 }
10697 }
10698
Jeff Sharkey287bd832011-05-28 19:36:26 -070010699 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010701 // If the caller is restarting this app, then leave it in its
10702 // current lists and let the caller take care of it.
10703 if (restarting) {
10704 return;
10705 }
10706
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010707 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010708 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010710 mProcessNames.remove(app.processName, app.uid);
10711 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010712 if (mHeavyWeightProcess == app) {
10713 mHeavyWeightProcess = null;
10714 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010716 } else if (!app.removed) {
10717 // This app is persistent, so we need to keep its record around.
10718 // If it is not already on the pending app list, add it there
10719 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010720 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10721 mPersistentStartingProcesses.add(app);
10722 restart = true;
10723 }
10724 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010725 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10726 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010727 mProcessesOnHold.remove(app);
10728
The Android Open Source Project4df24232009-03-05 14:34:35 -080010729 if (app == mHomeProcess) {
10730 mHomeProcess = null;
10731 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010732 if (app == mPreviousProcess) {
10733 mPreviousProcess = null;
10734 }
10735
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010736 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010737 // We have components that still need to be running in the
10738 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010739 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010740 startProcessLocked(app, "restart", app.processName);
10741 } else if (app.pid > 0 && app.pid != MY_PID) {
10742 // Goodbye!
10743 synchronized (mPidsSelfLocked) {
10744 mPidsSelfLocked.remove(app.pid);
10745 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10746 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010747 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010748 }
10749 }
10750
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010751 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10752 // Look through the content providers we are waiting to have launched,
10753 // and if any run in this process then either schedule a restart of
10754 // the process or kill the client waiting for it if this process has
10755 // gone bad.
10756 int NL = mLaunchingProviders.size();
10757 boolean restart = false;
10758 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010759 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010760 if (cpr.launchingApp == app) {
10761 if (!alwaysBad && !app.bad) {
10762 restart = true;
10763 } else {
10764 removeDyingProviderLocked(app, cpr);
10765 NL = mLaunchingProviders.size();
10766 }
10767 }
10768 }
10769 return restart;
10770 }
10771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 // =========================================================
10773 // SERVICES
10774 // =========================================================
10775
10776 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10777 ActivityManager.RunningServiceInfo info =
10778 new ActivityManager.RunningServiceInfo();
10779 info.service = r.name;
10780 if (r.app != null) {
10781 info.pid = r.app.pid;
10782 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010783 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 info.process = r.processName;
10785 info.foreground = r.isForeground;
10786 info.activeSince = r.createTime;
10787 info.started = r.startRequested;
10788 info.clientCount = r.connections.size();
10789 info.crashCount = r.crashCount;
10790 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010791 if (r.isForeground) {
10792 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10793 }
10794 if (r.startRequested) {
10795 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10796 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010797 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010798 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10799 }
10800 if (r.app != null && r.app.persistent) {
10801 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10802 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010803
10804 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10805 for (int i=0; i<connl.size(); i++) {
10806 ConnectionRecord conn = connl.get(i);
10807 if (conn.clientLabel != 0) {
10808 info.clientPackage = conn.binding.client.info.packageName;
10809 info.clientLabel = conn.clientLabel;
10810 return info;
10811 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010812 }
10813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010814 return info;
10815 }
10816
10817 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10818 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010819 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010820 synchronized (this) {
10821 ArrayList<ActivityManager.RunningServiceInfo> res
10822 = new ArrayList<ActivityManager.RunningServiceInfo>();
10823
Amith Yamasani742a6712011-05-04 14:49:28 -070010824 int userId = UserId.getUserId(Binder.getCallingUid());
10825 if (mServiceMap.getAllServices(userId).size() > 0) {
10826 Iterator<ServiceRecord> it
10827 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010828 while (it.hasNext() && res.size() < maxNum) {
10829 res.add(makeRunningServiceInfoLocked(it.next()));
10830 }
10831 }
10832
10833 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10834 ServiceRecord r = mRestartingServices.get(i);
10835 ActivityManager.RunningServiceInfo info =
10836 makeRunningServiceInfoLocked(r);
10837 info.restarting = r.nextRestartTime;
10838 res.add(info);
10839 }
10840
10841 return res;
10842 }
10843 }
10844
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010845 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010846 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010847 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010848 int userId = UserId.getUserId(Binder.getCallingUid());
10849 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010850 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010851 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10852 for (int i=0; i<conn.size(); i++) {
10853 if (conn.get(i).clientIntent != null) {
10854 return conn.get(i).clientIntent;
10855 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010856 }
10857 }
10858 }
10859 }
10860 return null;
10861 }
10862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 private final ServiceRecord findServiceLocked(ComponentName name,
10864 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010865 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 return r == token ? r : null;
10867 }
10868
10869 private final class ServiceLookupResult {
10870 final ServiceRecord record;
10871 final String permission;
10872
10873 ServiceLookupResult(ServiceRecord _record, String _permission) {
10874 record = _record;
10875 permission = _permission;
10876 }
10877 };
10878
10879 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010880 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 ServiceRecord r = null;
10882 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010883 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010884 }
10885 if (r == null) {
10886 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010887 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 }
10889
10890 if (r == null) {
10891 try {
10892 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010893 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010894 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 ServiceInfo sInfo =
10896 rInfo != null ? rInfo.serviceInfo : null;
10897 if (sInfo == null) {
10898 return null;
10899 }
10900
10901 ComponentName name = new ComponentName(
10902 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010903 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 } catch (RemoteException ex) {
10905 // pm is in same process, this will never happen.
10906 }
10907 }
10908 if (r != null) {
10909 int callingPid = Binder.getCallingPid();
10910 int callingUid = Binder.getCallingUid();
10911 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010912 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010913 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010914 if (!r.exported) {
10915 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10916 + " from pid=" + callingPid
10917 + ", uid=" + callingUid
10918 + " that is not exported from uid " + r.appInfo.uid);
10919 return new ServiceLookupResult(null, "not exported from uid "
10920 + r.appInfo.uid);
10921 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010922 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 + " from pid=" + callingPid
10924 + ", uid=" + callingUid
10925 + " requires " + r.permission);
10926 return new ServiceLookupResult(null, r.permission);
10927 }
10928 return new ServiceLookupResult(r, null);
10929 }
10930 return null;
10931 }
10932
10933 private class ServiceRestarter implements Runnable {
10934 private ServiceRecord mService;
10935
10936 void setService(ServiceRecord service) {
10937 mService = service;
10938 }
10939
10940 public void run() {
10941 synchronized(ActivityManagerService.this) {
10942 performServiceRestartLocked(mService);
10943 }
10944 }
10945 }
10946
10947 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010948 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010949 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010950 if (DEBUG_SERVICE)
10951 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010952 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010955 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010957 if (r == null) {
10958 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010959 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010961 if (r == null) {
10962 try {
10963 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010964 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010965 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 ServiceInfo sInfo =
10967 rInfo != null ? rInfo.serviceInfo : null;
10968 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010969 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 ": not found");
10971 return null;
10972 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010973 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010974 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10975 userId = 0;
10976 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010977 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 ComponentName name = new ComponentName(
10980 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010981 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010983 Intent.FilterComparison filter = new Intent.FilterComparison(
10984 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010985 ServiceRestarter res = new ServiceRestarter();
10986 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10987 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10988 synchronized (stats) {
10989 ss = stats.getServiceStatsLocked(
10990 sInfo.applicationInfo.uid, sInfo.packageName,
10991 sInfo.name);
10992 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010993 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010995 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10996 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997
10998 // Make sure this component isn't in the pending list.
10999 int N = mPendingServices.size();
11000 for (int i=0; i<N; i++) {
11001 ServiceRecord pr = mPendingServices.get(i);
11002 if (pr.name.equals(name)) {
11003 mPendingServices.remove(i);
11004 i--;
11005 N--;
11006 }
11007 }
11008 }
11009 } catch (RemoteException ex) {
11010 // pm is in same process, this will never happen.
11011 }
11012 }
11013 if (r != null) {
11014 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011015 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011017 if (!r.exported) {
11018 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11019 + " from pid=" + callingPid
11020 + ", uid=" + callingUid
11021 + " that is not exported from uid " + r.appInfo.uid);
11022 return new ServiceLookupResult(null, "not exported from uid "
11023 + r.appInfo.uid);
11024 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011025 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011026 + " from pid=" + callingPid
11027 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 + " requires " + r.permission);
11029 return new ServiceLookupResult(null, r.permission);
11030 }
11031 return new ServiceLookupResult(r, null);
11032 }
11033 return null;
11034 }
11035
Dianne Hackborn287952c2010-09-22 22:34:31 -070011036 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11037 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11038 + why + " of " + r + " in app " + r.app);
11039 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11040 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 long now = SystemClock.uptimeMillis();
11042 if (r.executeNesting == 0 && r.app != null) {
11043 if (r.app.executingServices.size() == 0) {
11044 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11045 msg.obj = r.app;
11046 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11047 }
11048 r.app.executingServices.add(r);
11049 }
11050 r.executeNesting++;
11051 r.executingStart = now;
11052 }
11053
11054 private final void sendServiceArgsLocked(ServiceRecord r,
11055 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011056 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 if (N == 0) {
11058 return;
11059 }
11060
Dianne Hackborn39792d22010-08-19 18:01:52 -070011061 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011062 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011063 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011064 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11065 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011066 if (si.intent == null && N > 1) {
11067 // If somehow we got a dummy null intent in the middle,
11068 // then skip it. DO NOT skip a null intent when it is
11069 // the only one in the list -- this is to support the
11070 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011071 continue;
11072 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011073 si.deliveredTime = SystemClock.uptimeMillis();
11074 r.deliveredStarts.add(si);
11075 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011076 if (si.neededGrants != null) {
11077 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11078 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011079 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011080 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 if (!oomAdjusted) {
11082 oomAdjusted = true;
11083 updateOomAdjLocked(r.app);
11084 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011085 int flags = 0;
Dianne Hackbornd8f10242012-05-08 17:14:58 -070011086 if (si.deliveryCount > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011087 flags |= Service.START_FLAG_RETRY;
11088 }
11089 if (si.doneExecutingCount > 0) {
11090 flags |= Service.START_FLAG_REDELIVERY;
11091 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011092 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011093 } catch (RemoteException e) {
11094 // Remote process gone... we'll let the normal cleanup take
11095 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011096 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011097 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011098 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011099 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 break;
11101 }
11102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 }
11104
11105 private final boolean requestServiceBindingLocked(ServiceRecord r,
11106 IntentBindRecord i, boolean rebind) {
11107 if (r.app == null || r.app.thread == null) {
11108 // If service is not currently running, can't yet bind.
11109 return false;
11110 }
11111 if ((!i.requested || rebind) && i.apps.size() > 0) {
11112 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011113 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11115 if (!rebind) {
11116 i.requested = true;
11117 }
11118 i.hasBound = true;
11119 i.doRebind = false;
11120 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011121 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 return false;
11123 }
11124 }
11125 return true;
11126 }
11127
11128 private final void requestServiceBindingsLocked(ServiceRecord r) {
11129 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11130 while (bindings.hasNext()) {
11131 IntentBindRecord i = bindings.next();
11132 if (!requestServiceBindingLocked(r, i, false)) {
11133 break;
11134 }
11135 }
11136 }
11137
11138 private final void realStartServiceLocked(ServiceRecord r,
11139 ProcessRecord app) throws RemoteException {
11140 if (app.thread == null) {
11141 throw new RemoteException();
11142 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011143 if (DEBUG_MU)
11144 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011145 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011147 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148
11149 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011150 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011151 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152
11153 boolean created = false;
11154 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011155 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011156 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011157 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011159 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011160 synchronized (r.stats.getBatteryStats()) {
11161 r.stats.startLaunchedLocked();
11162 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011163 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011164 app.thread.scheduleCreateService(r, r.serviceInfo,
11165 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011166 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 created = true;
11168 } finally {
11169 if (!created) {
11170 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011171 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011172 }
11173 }
11174
11175 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011176
11177 // If the service is in the started state, and there are no
11178 // pending arguments, then fake up one so its onStartCommand() will
11179 // be called.
11180 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011181 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011182 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011183 }
11184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011185 sendServiceArgsLocked(r, true);
11186 }
11187
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011188 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11189 boolean allowCancel) {
11190 boolean canceled = false;
11191
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011192 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011193 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011194 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011195
Dianne Hackborn070783f2010-12-29 16:46:28 -080011196 if ((r.serviceInfo.applicationInfo.flags
11197 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11198 minDuration /= 4;
11199 }
11200
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011201 // Any delivered but not yet finished starts should be put back
11202 // on the pending list.
11203 final int N = r.deliveredStarts.size();
11204 if (N > 0) {
11205 for (int i=N-1; i>=0; i--) {
11206 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011207 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011208 if (si.intent == null) {
11209 // We'll generate this again if needed.
11210 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11211 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11212 r.pendingStarts.add(0, si);
11213 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11214 dur *= 2;
11215 if (minDuration < dur) minDuration = dur;
11216 if (resetTime < dur) resetTime = dur;
11217 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011218 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011219 + r.name);
11220 canceled = true;
11221 }
11222 }
11223 r.deliveredStarts.clear();
11224 }
11225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011226 r.totalRestartCount++;
11227 if (r.restartDelay == 0) {
11228 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011229 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 } else {
11231 // If it has been a "reasonably long time" since the service
11232 // was started, then reset our restart duration back to
11233 // the beginning, so we don't infinitely increase the duration
11234 // on a service that just occasionally gets killed (which is
11235 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011236 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011238 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011240 if ((r.serviceInfo.applicationInfo.flags
11241 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11242 // Services in peristent processes will restart much more
11243 // quickly, since they are pretty important. (Think SystemUI).
11244 r.restartDelay += minDuration/2;
11245 } else {
11246 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11247 if (r.restartDelay < minDuration) {
11248 r.restartDelay = minDuration;
11249 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 }
11252 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011253
11254 r.nextRestartTime = now + r.restartDelay;
11255
11256 // Make sure that we don't end up restarting a bunch of services
11257 // all at the same time.
11258 boolean repeat;
11259 do {
11260 repeat = false;
11261 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11262 ServiceRecord r2 = mRestartingServices.get(i);
11263 if (r2 != r && r.nextRestartTime
11264 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11265 && r.nextRestartTime
11266 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11267 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11268 r.restartDelay = r.nextRestartTime - now;
11269 repeat = true;
11270 break;
11271 }
11272 }
11273 } while (repeat);
11274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011275 if (!mRestartingServices.contains(r)) {
11276 mRestartingServices.add(r);
11277 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011278
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011279 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011281 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011282 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011283 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011284 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011286 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 r.shortName, r.restartDelay);
11288
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011289 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011290 }
11291
11292 final void performServiceRestartLocked(ServiceRecord r) {
11293 if (!mRestartingServices.contains(r)) {
11294 return;
11295 }
11296 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11297 }
11298
11299 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11300 if (r.restartDelay == 0) {
11301 return false;
11302 }
11303 r.resetRestartCounter();
11304 mRestartingServices.remove(r);
11305 mHandler.removeCallbacks(r.restarter);
11306 return true;
11307 }
11308
11309 private final boolean bringUpServiceLocked(ServiceRecord r,
11310 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011311 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011312 //r.dump(" ");
11313
Dianne Hackborn36124872009-10-08 16:22:03 -070011314 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011315 sendServiceArgsLocked(r, false);
11316 return true;
11317 }
11318
11319 if (!whileRestarting && r.restartDelay > 0) {
11320 // If waiting for a restart, then do nothing.
11321 return true;
11322 }
11323
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011324 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011326 // We are now bringing the service up, so no longer in the
11327 // restarting state.
11328 mRestartingServices.remove(r);
11329
Dianne Hackborne7f97212011-02-24 14:40:20 -080011330 // Service is now being launched, its package can't be stopped.
11331 try {
11332 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011333 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011334 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011335 } catch (IllegalArgumentException e) {
11336 Slog.w(TAG, "Failed trying to unstop package "
11337 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011338 }
11339
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011340 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011342 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011344 if (!isolated) {
11345 app = getProcessRecordLocked(appName, r.appInfo.uid);
11346 if (DEBUG_MU)
11347 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11348 if (app != null && app.thread != null) {
11349 try {
11350 app.addPackage(r.appInfo.packageName);
11351 realStartServiceLocked(r, app);
11352 return true;
11353 } catch (RemoteException e) {
11354 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11355 }
11356
11357 // If a dead object exception was thrown -- fall through to
11358 // restart the application.
11359 }
11360 } else {
11361 // If this service runs in an isolated process, then each time
11362 // we call startProcessLocked() we will get a new isolated
11363 // process, starting another process if we are currently waiting
11364 // for a previous process to come up. To deal with this, we store
11365 // in the service any current isolated process it is running in or
11366 // waiting to have come up.
11367 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 }
11369
Dianne Hackborn36124872009-10-08 16:22:03 -070011370 // Not running -- get it started, and enqueue this service record
11371 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011372 if (app == null) {
11373 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11374 "service", r.name, false, isolated)) == null) {
11375 Slog.w(TAG, "Unable to launch app "
11376 + r.appInfo.packageName + "/"
11377 + r.appInfo.uid + " for service "
11378 + r.intent.getIntent() + ": process is bad");
11379 bringDownServiceLocked(r, true);
11380 return false;
11381 }
11382 if (isolated) {
11383 r.isolatedProc = app;
11384 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011385 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 mPendingServices.add(r);
11389 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011391 return true;
11392 }
11393
11394 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011395 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 //r.dump(" ");
11397
11398 // Does it still need to run?
11399 if (!force && r.startRequested) {
11400 return;
11401 }
11402 if (r.connections.size() > 0) {
11403 if (!force) {
11404 // XXX should probably keep a count of the number of auto-create
11405 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011406 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011408 ArrayList<ConnectionRecord> cr = it.next();
11409 for (int i=0; i<cr.size(); i++) {
11410 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11411 return;
11412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 }
11414 }
11415 }
11416
11417 // Report to all of the connections that the service is no longer
11418 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011419 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011421 ArrayList<ConnectionRecord> c = it.next();
11422 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011423 ConnectionRecord cr = c.get(i);
11424 // There is still a connection to the service that is
11425 // being brought down. Mark it as dead.
11426 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011427 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011428 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011429 } catch (Exception e) {
11430 Slog.w(TAG, "Failure disconnecting service " + r.name +
11431 " to connection " + c.get(i).conn.asBinder() +
11432 " (in " + c.get(i).binding.client.processName + ")", e);
11433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 }
11435 }
11436 }
11437
11438 // Tell the service that it has been unbound.
11439 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11440 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11441 while (it.hasNext()) {
11442 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011443 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 + ": hasBound=" + ibr.hasBound);
11445 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11446 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011447 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 updateOomAdjLocked(r.app);
11449 ibr.hasBound = false;
11450 r.app.thread.scheduleUnbindService(r,
11451 ibr.intent.getIntent());
11452 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011453 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011454 + r.shortName, e);
11455 serviceDoneExecutingLocked(r, true);
11456 }
11457 }
11458 }
11459 }
11460
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011461 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011462 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011463 System.identityHashCode(r), r.shortName,
11464 (r.app != null) ? r.app.pid : -1);
11465
Amith Yamasani742a6712011-05-04 14:49:28 -070011466 mServiceMap.removeServiceByName(r.name, r.userId);
11467 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011468 r.totalRestartCount = 0;
11469 unscheduleServiceRestartLocked(r);
11470
11471 // Also make sure it is not on the pending list.
11472 int N = mPendingServices.size();
11473 for (int i=0; i<N; i++) {
11474 if (mPendingServices.get(i) == r) {
11475 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011476 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 i--;
11478 N--;
11479 }
11480 }
11481
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011482 r.cancelNotification();
11483 r.isForeground = false;
11484 r.foregroundId = 0;
11485 r.foregroundNoti = null;
11486
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011487 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011488 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011489 r.pendingStarts.clear();
11490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 if (r.app != null) {
11492 synchronized (r.stats.getBatteryStats()) {
11493 r.stats.stopLaunchedLocked();
11494 }
11495 r.app.services.remove(r);
11496 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011498 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 mStoppingServices.add(r);
11500 updateOomAdjLocked(r.app);
11501 r.app.thread.scheduleStopService(r);
11502 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011503 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 + r.shortName, e);
11505 serviceDoneExecutingLocked(r, true);
11506 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011507 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011508 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011509 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011510 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011511 }
11512 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011513 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011514 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011515 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011516
11517 if (r.bindings.size() > 0) {
11518 r.bindings.clear();
11519 }
11520
11521 if (r.restarter instanceof ServiceRestarter) {
11522 ((ServiceRestarter)r.restarter).setService(null);
11523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 }
11525
11526 ComponentName startServiceLocked(IApplicationThread caller,
11527 Intent service, String resolvedType,
11528 int callingPid, int callingUid) {
11529 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011530 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531 + " type=" + resolvedType + " args=" + service.getExtras());
11532
11533 if (caller != null) {
11534 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11535 if (callerApp == null) {
11536 throw new SecurityException(
11537 "Unable to find app for caller " + caller
11538 + " (pid=" + Binder.getCallingPid()
11539 + ") when starting service " + service);
11540 }
11541 }
11542
11543 ServiceLookupResult res =
11544 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011545 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 if (res == null) {
11547 return null;
11548 }
11549 if (res.record == null) {
11550 return new ComponentName("!", res.permission != null
11551 ? res.permission : "private to package");
11552 }
11553 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011554 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11555 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011556 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011557 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 }
11559 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011560 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011561 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011562 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011563 r.lastActivity = SystemClock.uptimeMillis();
11564 synchronized (r.stats.getBatteryStats()) {
11565 r.stats.startRunningLocked();
11566 }
11567 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11568 return new ComponentName("!", "Service process is bad");
11569 }
11570 return r.name;
11571 }
11572 }
11573
11574 public ComponentName startService(IApplicationThread caller, Intent service,
11575 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011576 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011577 // Refuse possible leaked file descriptors
11578 if (service != null && service.hasFileDescriptors() == true) {
11579 throw new IllegalArgumentException("File descriptors passed in Intent");
11580 }
11581
Amith Yamasani742a6712011-05-04 14:49:28 -070011582 if (DEBUG_SERVICE)
11583 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011584 synchronized(this) {
11585 final int callingPid = Binder.getCallingPid();
11586 final int callingUid = Binder.getCallingUid();
11587 final long origId = Binder.clearCallingIdentity();
11588 ComponentName res = startServiceLocked(caller, service,
11589 resolvedType, callingPid, callingUid);
11590 Binder.restoreCallingIdentity(origId);
11591 return res;
11592 }
11593 }
11594
11595 ComponentName startServiceInPackage(int uid,
11596 Intent service, String resolvedType) {
11597 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011598 if (DEBUG_SERVICE)
11599 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600 final long origId = Binder.clearCallingIdentity();
11601 ComponentName res = startServiceLocked(null, service,
11602 resolvedType, -1, uid);
11603 Binder.restoreCallingIdentity(origId);
11604 return res;
11605 }
11606 }
11607
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011608 private void stopServiceLocked(ServiceRecord service) {
11609 synchronized (service.stats.getBatteryStats()) {
11610 service.stats.stopRunningLocked();
11611 }
11612 service.startRequested = false;
11613 service.callStart = false;
11614 bringDownServiceLocked(service, false);
11615 }
11616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 public int stopService(IApplicationThread caller, Intent service,
11618 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011619 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 // Refuse possible leaked file descriptors
11621 if (service != null && service.hasFileDescriptors() == true) {
11622 throw new IllegalArgumentException("File descriptors passed in Intent");
11623 }
11624
11625 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011626 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 + " type=" + resolvedType);
11628
11629 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11630 if (caller != null && callerApp == null) {
11631 throw new SecurityException(
11632 "Unable to find app for caller " + caller
11633 + " (pid=" + Binder.getCallingPid()
11634 + ") when stopping service " + service);
11635 }
11636
11637 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011638 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11639 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640 if (r != null) {
11641 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011643 try {
11644 stopServiceLocked(r.record);
11645 } finally {
11646 Binder.restoreCallingIdentity(origId);
11647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011648 return 1;
11649 }
11650 return -1;
11651 }
11652 }
11653
11654 return 0;
11655 }
11656
11657 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011658 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 // Refuse possible leaked file descriptors
11660 if (service != null && service.hasFileDescriptors() == true) {
11661 throw new IllegalArgumentException("File descriptors passed in Intent");
11662 }
11663
11664 IBinder ret = null;
11665
11666 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011667 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11668 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011669
11670 if (r != null) {
11671 // r.record is null if findServiceLocked() failed the caller permission check
11672 if (r.record == null) {
11673 throw new SecurityException(
11674 "Permission Denial: Accessing service " + r.record.name
11675 + " from pid=" + Binder.getCallingPid()
11676 + ", uid=" + Binder.getCallingUid()
11677 + " requires " + r.permission);
11678 }
11679 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11680 if (ib != null) {
11681 ret = ib.binder;
11682 }
11683 }
11684 }
11685
11686 return ret;
11687 }
11688
11689 public boolean stopServiceToken(ComponentName className, IBinder token,
11690 int startId) {
11691 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011692 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693 + " " + token + " startId=" + startId);
11694 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011695 if (r != null) {
11696 if (startId >= 0) {
11697 // Asked to only stop if done with all work. Note that
11698 // to avoid leaks, we will take this as dropping all
11699 // start items up to and including this one.
11700 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11701 if (si != null) {
11702 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011703 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11704 cur.removeUriPermissionsLocked();
11705 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011706 break;
11707 }
11708 }
11709 }
11710
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011711 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011712 return false;
11713 }
11714
11715 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011716 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011717 + " is last, but have " + r.deliveredStarts.size()
11718 + " remaining args");
11719 }
11720 }
11721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 synchronized (r.stats.getBatteryStats()) {
11723 r.stats.stopRunningLocked();
11724 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011725 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726 }
11727 final long origId = Binder.clearCallingIdentity();
11728 bringDownServiceLocked(r, false);
11729 Binder.restoreCallingIdentity(origId);
11730 return true;
11731 }
11732 }
11733 return false;
11734 }
11735
11736 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011737 int id, Notification notification, boolean removeNotification) {
11738 final long origId = Binder.clearCallingIdentity();
11739 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 synchronized(this) {
11741 ServiceRecord r = findServiceLocked(className, token);
11742 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011743 if (id != 0) {
11744 if (notification == null) {
11745 throw new IllegalArgumentException("null notification");
11746 }
11747 if (r.foregroundId != id) {
11748 r.cancelNotification();
11749 r.foregroundId = id;
11750 }
11751 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11752 r.foregroundNoti = notification;
11753 r.isForeground = true;
11754 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011755 if (r.app != null) {
11756 updateServiceForegroundLocked(r.app, true);
11757 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011758 } else {
11759 if (r.isForeground) {
11760 r.isForeground = false;
11761 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011762 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011763 updateServiceForegroundLocked(r.app, true);
11764 }
11765 }
11766 if (removeNotification) {
11767 r.cancelNotification();
11768 r.foregroundId = 0;
11769 r.foregroundNoti = null;
11770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011771 }
11772 }
11773 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011774 } finally {
11775 Binder.restoreCallingIdentity(origId);
11776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777 }
11778
11779 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11780 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011781 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011782 if (sr.isForeground) {
11783 anyForeground = true;
11784 break;
11785 }
11786 }
11787 if (anyForeground != proc.foregroundServices) {
11788 proc.foregroundServices = anyForeground;
11789 if (oomAdj) {
11790 updateOomAdjLocked();
11791 }
11792 }
11793 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011794
11795 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11796 boolean result = false;
11797 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11798 result = false;
11799 } else if (componentProcessName == aInfo.packageName) {
11800 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11801 } else if ("system".equals(componentProcessName)) {
11802 result = true;
11803 }
11804 if (DEBUG_MU) {
11805 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11806 }
11807 return result;
11808 }
11809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 public int bindService(IApplicationThread caller, IBinder token,
11811 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011812 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011813 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 // Refuse possible leaked file descriptors
11815 if (service != null && service.hasFileDescriptors() == true) {
11816 throw new IllegalArgumentException("File descriptors passed in Intent");
11817 }
11818
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011819 checkValidCaller(Binder.getCallingUid(), userId);
11820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011822 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823 + " type=" + resolvedType + " conn=" + connection.asBinder()
11824 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011825 if (DEBUG_MU)
11826 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11827 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11829 if (callerApp == null) {
11830 throw new SecurityException(
11831 "Unable to find app for caller " + caller
11832 + " (pid=" + Binder.getCallingPid()
11833 + ") when binding service " + service);
11834 }
11835
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011836 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011838 activity = mMainStack.isInStackLocked(token);
11839 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011840 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011841 return 0;
11842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011843 }
11844
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011845 int clientLabel = 0;
11846 PendingIntent clientIntent = null;
11847
11848 if (callerApp.info.uid == Process.SYSTEM_UID) {
11849 // Hacky kind of thing -- allow system stuff to tell us
11850 // what they are, so we can report this elsewhere for
11851 // others to know why certain services are running.
11852 try {
11853 clientIntent = (PendingIntent)service.getParcelableExtra(
11854 Intent.EXTRA_CLIENT_INTENT);
11855 } catch (RuntimeException e) {
11856 }
11857 if (clientIntent != null) {
11858 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11859 if (clientLabel != 0) {
11860 // There are no useful extras in the intent, trash them.
11861 // System code calling with this stuff just needs to know
11862 // this will happen.
11863 service = service.cloneFilter();
11864 }
11865 }
11866 }
11867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868 ServiceLookupResult res =
11869 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011870 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011871 if (res == null) {
11872 return 0;
11873 }
11874 if (res.record == null) {
11875 return -1;
11876 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011877 if (isSingleton(res.record.processName, res.record.appInfo)) {
11878 userId = 0;
11879 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11880 Binder.getCallingUid(), 0);
11881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011882 ServiceRecord s = res.record;
11883
11884 final long origId = Binder.clearCallingIdentity();
11885
11886 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011887 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011888 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889 }
11890
11891 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11892 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011893 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894
11895 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011896 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11897 if (clist == null) {
11898 clist = new ArrayList<ConnectionRecord>();
11899 s.connections.put(binder, clist);
11900 }
11901 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011902 b.connections.add(c);
11903 if (activity != null) {
11904 if (activity.connections == null) {
11905 activity.connections = new HashSet<ConnectionRecord>();
11906 }
11907 activity.connections.add(c);
11908 }
11909 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011910 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11911 b.client.hasAboveClient = true;
11912 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011913 clist = mServiceConnections.get(binder);
11914 if (clist == null) {
11915 clist = new ArrayList<ConnectionRecord>();
11916 mServiceConnections.put(binder, clist);
11917 }
11918 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011919
11920 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11921 s.lastActivity = SystemClock.uptimeMillis();
11922 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11923 return 0;
11924 }
11925 }
11926
11927 if (s.app != null) {
11928 // This could have made the service more important.
11929 updateOomAdjLocked(s.app);
11930 }
11931
Joe Onorato8a9b2202010-02-26 18:56:32 -080011932 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 + ": received=" + b.intent.received
11934 + " apps=" + b.intent.apps.size()
11935 + " doRebind=" + b.intent.doRebind);
11936
11937 if (s.app != null && b.intent.received) {
11938 // Service is already running, so we can immediately
11939 // publish the connection.
11940 try {
11941 c.conn.connected(s.name, b.intent.binder);
11942 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011943 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 + " to connection " + c.conn.asBinder()
11945 + " (in " + c.binding.client.processName + ")", e);
11946 }
11947
11948 // If this is the first app connected back to this binding,
11949 // and the service had previously asked to be told when
11950 // rebound, then do so.
11951 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11952 requestServiceBindingLocked(s, b.intent, true);
11953 }
11954 } else if (!b.intent.requested) {
11955 requestServiceBindingLocked(s, b.intent, false);
11956 }
11957
11958 Binder.restoreCallingIdentity(origId);
11959 }
11960
11961 return 1;
11962 }
11963
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011964 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011965 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966 IBinder binder = c.conn.asBinder();
11967 AppBindRecord b = c.binding;
11968 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011969 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11970 if (clist != null) {
11971 clist.remove(c);
11972 if (clist.size() == 0) {
11973 s.connections.remove(binder);
11974 }
11975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011976 b.connections.remove(c);
11977 if (c.activity != null && c.activity != skipAct) {
11978 if (c.activity.connections != null) {
11979 c.activity.connections.remove(c);
11980 }
11981 }
11982 if (b.client != skipApp) {
11983 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011984 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11985 b.client.updateHasAboveClientLocked();
11986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011988 clist = mServiceConnections.get(binder);
11989 if (clist != null) {
11990 clist.remove(c);
11991 if (clist.size() == 0) {
11992 mServiceConnections.remove(binder);
11993 }
11994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011995
11996 if (b.connections.size() == 0) {
11997 b.intent.apps.remove(b.client);
11998 }
11999
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012000 if (!c.serviceDead) {
12001 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12002 + ": shouldUnbind=" + b.intent.hasBound);
12003 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12004 && b.intent.hasBound) {
12005 try {
12006 bumpServiceExecutingLocked(s, "unbind");
12007 updateOomAdjLocked(s.app);
12008 b.intent.hasBound = false;
12009 // Assume the client doesn't want to know about a rebind;
12010 // we will deal with that later if it asks for one.
12011 b.intent.doRebind = false;
12012 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12013 } catch (Exception e) {
12014 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12015 serviceDoneExecutingLocked(s, true);
12016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012018
12019 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12020 bringDownServiceLocked(s, false);
12021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012022 }
12023 }
12024
12025 public boolean unbindService(IServiceConnection connection) {
12026 synchronized (this) {
12027 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012028 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012029 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12030 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012031 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012032 + connection.asBinder());
12033 return false;
12034 }
12035
12036 final long origId = Binder.clearCallingIdentity();
12037
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012038 while (clist.size() > 0) {
12039 ConnectionRecord r = clist.get(0);
12040 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012041
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012042 if (r.binding.service.app != null) {
12043 // This could have made the service less important.
12044 updateOomAdjLocked(r.binding.service.app);
12045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 }
12047
12048 Binder.restoreCallingIdentity(origId);
12049 }
12050
12051 return true;
12052 }
12053
12054 public void publishService(IBinder token, Intent intent, IBinder service) {
12055 // Refuse possible leaked file descriptors
12056 if (intent != null && intent.hasFileDescriptors() == true) {
12057 throw new IllegalArgumentException("File descriptors passed in Intent");
12058 }
12059
12060 synchronized(this) {
12061 if (!(token instanceof ServiceRecord)) {
12062 throw new IllegalArgumentException("Invalid service token");
12063 }
12064 ServiceRecord r = (ServiceRecord)token;
12065
12066 final long origId = Binder.clearCallingIdentity();
12067
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012068 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 + " " + intent + ": " + service);
12070 if (r != null) {
12071 Intent.FilterComparison filter
12072 = new Intent.FilterComparison(intent);
12073 IntentBindRecord b = r.bindings.get(filter);
12074 if (b != null && !b.received) {
12075 b.binder = service;
12076 b.requested = true;
12077 b.received = true;
12078 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012079 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012080 = r.connections.values().iterator();
12081 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012082 ArrayList<ConnectionRecord> clist = it.next();
12083 for (int i=0; i<clist.size(); i++) {
12084 ConnectionRecord c = clist.get(i);
12085 if (!filter.equals(c.binding.intent.intent)) {
12086 if (DEBUG_SERVICE) Slog.v(
12087 TAG, "Not publishing to: " + c);
12088 if (DEBUG_SERVICE) Slog.v(
12089 TAG, "Bound intent: " + c.binding.intent.intent);
12090 if (DEBUG_SERVICE) Slog.v(
12091 TAG, "Published intent: " + intent);
12092 continue;
12093 }
12094 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12095 try {
12096 c.conn.connected(r.name, service);
12097 } catch (Exception e) {
12098 Slog.w(TAG, "Failure sending service " + r.name +
12099 " to connection " + c.conn.asBinder() +
12100 " (in " + c.binding.client.processName + ")", e);
12101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012102 }
12103 }
12104 }
12105 }
12106
12107 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12108
12109 Binder.restoreCallingIdentity(origId);
12110 }
12111 }
12112 }
12113
12114 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12115 // Refuse possible leaked file descriptors
12116 if (intent != null && intent.hasFileDescriptors() == true) {
12117 throw new IllegalArgumentException("File descriptors passed in Intent");
12118 }
12119
12120 synchronized(this) {
12121 if (!(token instanceof ServiceRecord)) {
12122 throw new IllegalArgumentException("Invalid service token");
12123 }
12124 ServiceRecord r = (ServiceRecord)token;
12125
12126 final long origId = Binder.clearCallingIdentity();
12127
12128 if (r != null) {
12129 Intent.FilterComparison filter
12130 = new Intent.FilterComparison(intent);
12131 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012132 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133 + " at " + b + ": apps="
12134 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012135
12136 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012137 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012138 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012139 // Applications have already bound since the last
12140 // unbind, so just rebind right here.
12141 requestServiceBindingLocked(r, b, true);
12142 } else {
12143 // Note to tell the service the next time there is
12144 // a new client.
12145 b.doRebind = true;
12146 }
12147 }
12148
Per Edelberg78f9fff2010-08-30 20:01:35 +020012149 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012150
12151 Binder.restoreCallingIdentity(origId);
12152 }
12153 }
12154 }
12155
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012156 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012157 synchronized(this) {
12158 if (!(token instanceof ServiceRecord)) {
12159 throw new IllegalArgumentException("Invalid service token");
12160 }
12161 ServiceRecord r = (ServiceRecord)token;
12162 boolean inStopping = mStoppingServices.contains(token);
12163 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012164 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012165 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012166 + " with incorrect token: given " + token
12167 + ", expected " + r);
12168 return;
12169 }
12170
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012171 if (type == 1) {
12172 // This is a call from a service start... take care of
12173 // book-keeping.
12174 r.callStart = true;
12175 switch (res) {
12176 case Service.START_STICKY_COMPATIBILITY:
12177 case Service.START_STICKY: {
12178 // We are done with the associated start arguments.
12179 r.findDeliveredStart(startId, true);
12180 // Don't stop if killed.
12181 r.stopIfKilled = false;
12182 break;
12183 }
12184 case Service.START_NOT_STICKY: {
12185 // We are done with the associated start arguments.
12186 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012187 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012188 // There is no more work, and this service
12189 // doesn't want to hang around if killed.
12190 r.stopIfKilled = true;
12191 }
12192 break;
12193 }
12194 case Service.START_REDELIVER_INTENT: {
12195 // We'll keep this item until they explicitly
12196 // call stop for it, but keep track of the fact
12197 // that it was delivered.
12198 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12199 if (si != null) {
12200 si.deliveryCount = 0;
12201 si.doneExecutingCount++;
12202 // Don't stop if killed.
12203 r.stopIfKilled = true;
12204 }
12205 break;
12206 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012207 case Service.START_TASK_REMOVED_COMPLETE: {
12208 // Special processing for onTaskRemoved(). Don't
12209 // impact normal onStartCommand() processing.
12210 r.findDeliveredStart(startId, true);
12211 break;
12212 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012213 default:
12214 throw new IllegalArgumentException(
12215 "Unknown service start result: " + res);
12216 }
12217 if (res == Service.START_STICKY_COMPATIBILITY) {
12218 r.callStart = false;
12219 }
12220 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012221 if (DEBUG_MU)
12222 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12223 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224 final long origId = Binder.clearCallingIdentity();
12225 serviceDoneExecutingLocked(r, inStopping);
12226 Binder.restoreCallingIdentity(origId);
12227 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012228 Slog.w(TAG, "Done executing unknown service from pid "
12229 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 }
12231 }
12232 }
12233
12234 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012235 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12236 + ": nesting=" + r.executeNesting
12237 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012238 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239 r.executeNesting--;
12240 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012241 if (DEBUG_SERVICE) Slog.v(TAG,
12242 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012243 r.app.executingServices.remove(r);
12244 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012245 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12246 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012247 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12248 }
12249 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012250 if (DEBUG_SERVICE) Slog.v(TAG,
12251 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012252 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012253 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012254 }
12255 updateOomAdjLocked(r.app);
12256 }
12257 }
12258
12259 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012260 String anrMessage = null;
12261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012262 synchronized(this) {
12263 if (proc.executingServices.size() == 0 || proc.thread == null) {
12264 return;
12265 }
12266 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12267 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12268 ServiceRecord timeout = null;
12269 long nextTime = 0;
12270 while (it.hasNext()) {
12271 ServiceRecord sr = it.next();
12272 if (sr.executingStart < maxTime) {
12273 timeout = sr;
12274 break;
12275 }
12276 if (sr.executingStart > nextTime) {
12277 nextTime = sr.executingStart;
12278 }
12279 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012280 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012281 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012282 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 } else {
12284 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12285 msg.obj = proc;
12286 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12287 }
12288 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012289
12290 if (anrMessage != null) {
12291 appNotResponding(proc, null, null, anrMessage);
12292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012293 }
12294
12295 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012296 // BACKUP AND RESTORE
12297 // =========================================================
12298
12299 // Cause the target app to be launched if necessary and its backup agent
12300 // instantiated. The backup agent will invoke backupAgentCreated() on the
12301 // activity manager to announce its creation.
12302 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012303 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012304 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12305
12306 synchronized(this) {
12307 // !!! TODO: currently no check here that we're already bound
12308 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12309 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12310 synchronized (stats) {
12311 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12312 }
12313
Dianne Hackborne7f97212011-02-24 14:40:20 -080012314 // Backup agent is now in use, its package can't be stopped.
12315 try {
12316 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012317 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012318 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012319 } catch (IllegalArgumentException e) {
12320 Slog.w(TAG, "Failed trying to unstop package "
12321 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012322 }
12323
Christopher Tate181fafa2009-05-14 11:12:14 -070012324 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012325 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12326 ? new ComponentName(app.packageName, app.backupAgentName)
12327 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012328 // startProcessLocked() returns existing proc's record if it's already running
12329 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012330 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012331 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012332 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012333 return false;
12334 }
12335
12336 r.app = proc;
12337 mBackupTarget = r;
12338 mBackupAppName = app.packageName;
12339
Christopher Tate6fa95972009-06-05 18:43:55 -070012340 // Try not to kill the process during backup
12341 updateOomAdjLocked(proc);
12342
Christopher Tate181fafa2009-05-14 11:12:14 -070012343 // If the process is already attached, schedule the creation of the backup agent now.
12344 // If it is not yet live, this will be done when it attaches to the framework.
12345 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012346 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012347 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012348 proc.thread.scheduleCreateBackupAgent(app,
12349 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012350 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012351 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012352 }
12353 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012354 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012355 }
12356 // Invariants: at this point, the target app process exists and the application
12357 // is either already running or in the process of coming up. mBackupTarget and
12358 // mBackupAppName describe the app, so that when it binds back to the AM we
12359 // know that it's scheduled for a backup-agent operation.
12360 }
12361
12362 return true;
12363 }
12364
12365 // A backup agent has just come up
12366 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012367 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012368 + " = " + agent);
12369
12370 synchronized(this) {
12371 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012372 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012373 return;
12374 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012375 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012376
Dianne Hackborn06740692010-09-22 22:46:21 -070012377 long oldIdent = Binder.clearCallingIdentity();
12378 try {
12379 IBackupManager bm = IBackupManager.Stub.asInterface(
12380 ServiceManager.getService(Context.BACKUP_SERVICE));
12381 bm.agentConnected(agentPackageName, agent);
12382 } catch (RemoteException e) {
12383 // can't happen; the backup manager service is local
12384 } catch (Exception e) {
12385 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12386 e.printStackTrace();
12387 } finally {
12388 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012389 }
12390 }
12391
12392 // done with this agent
12393 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012394 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012395 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012396 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012397 return;
12398 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012399
12400 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012401 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012402 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012403 return;
12404 }
12405
Christopher Tate181fafa2009-05-14 11:12:14 -070012406 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012407 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012408 return;
12409 }
12410
Christopher Tate6fa95972009-06-05 18:43:55 -070012411 ProcessRecord proc = mBackupTarget.app;
12412 mBackupTarget = null;
12413 mBackupAppName = null;
12414
12415 // Not backing this app up any more; reset its OOM adjustment
12416 updateOomAdjLocked(proc);
12417
Christopher Tatec7b31e32009-06-10 15:49:30 -070012418 // If the app crashed during backup, 'thread' will be null here
12419 if (proc.thread != null) {
12420 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012421 proc.thread.scheduleDestroyBackupAgent(appInfo,
12422 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012423 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012424 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012425 e.printStackTrace();
12426 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012427 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012428 }
12429 }
12430 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012431 // BROADCASTS
12432 // =========================================================
12433
Josh Bartel7f208742010-02-25 11:01:44 -060012434 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 List cur) {
12436 final ContentResolver resolver = mContext.getContentResolver();
12437 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12438 if (list == null) {
12439 return cur;
12440 }
12441 int N = list.size();
12442 for (int i=0; i<N; i++) {
12443 Intent intent = list.get(i);
12444 if (filter.match(resolver, intent, true, TAG) >= 0) {
12445 if (cur == null) {
12446 cur = new ArrayList<Intent>();
12447 }
12448 cur.add(intent);
12449 }
12450 }
12451 return cur;
12452 }
12453
Christopher Tatef46723b2012-01-26 14:19:24 -080012454 boolean isPendingBroadcastProcessLocked(int pid) {
12455 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12456 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012458
Christopher Tatef46723b2012-01-26 14:19:24 -080012459 void skipPendingBroadcastLocked(int pid) {
12460 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12461 for (BroadcastQueue queue : mBroadcastQueues) {
12462 queue.skipPendingBroadcastLocked(pid);
12463 }
12464 }
12465
12466 // The app just attached; send any pending broadcasts that it should receive
12467 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12468 boolean didSomething = false;
12469 for (BroadcastQueue queue : mBroadcastQueues) {
12470 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012471 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012472 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012473 }
12474
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012475 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012476 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012477 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 synchronized(this) {
12479 ProcessRecord callerApp = null;
12480 if (caller != null) {
12481 callerApp = getRecordForAppLocked(caller);
12482 if (callerApp == null) {
12483 throw new SecurityException(
12484 "Unable to find app for caller " + caller
12485 + " (pid=" + Binder.getCallingPid()
12486 + ") when registering receiver " + receiver);
12487 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012488 if (callerApp.info.uid != Process.SYSTEM_UID &&
12489 !callerApp.pkgList.contains(callerPackage)) {
12490 throw new SecurityException("Given caller package " + callerPackage
12491 + " is not running in process " + callerApp);
12492 }
12493 } else {
12494 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012495 }
12496
12497 List allSticky = null;
12498
12499 // Look for any matching sticky broadcasts...
12500 Iterator actions = filter.actionsIterator();
12501 if (actions != null) {
12502 while (actions.hasNext()) {
12503 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012504 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012505 }
12506 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012507 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 }
12509
12510 // The first sticky in the list is returned directly back to
12511 // the client.
12512 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12513
Joe Onorato8a9b2202010-02-26 18:56:32 -080012514 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 + ": " + sticky);
12516
12517 if (receiver == null) {
12518 return sticky;
12519 }
12520
12521 ReceiverList rl
12522 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12523 if (rl == null) {
12524 rl = new ReceiverList(this, callerApp,
12525 Binder.getCallingPid(),
12526 Binder.getCallingUid(), receiver);
12527 if (rl.app != null) {
12528 rl.app.receivers.add(rl);
12529 } else {
12530 try {
12531 receiver.asBinder().linkToDeath(rl, 0);
12532 } catch (RemoteException e) {
12533 return sticky;
12534 }
12535 rl.linkedToDeath = true;
12536 }
12537 mRegisteredReceivers.put(receiver.asBinder(), rl);
12538 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012539 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 rl.add(bf);
12541 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012542 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 }
12544 mReceiverResolver.addFilter(bf);
12545
12546 // Enqueue broadcasts for all existing stickies that match
12547 // this filter.
12548 if (allSticky != null) {
12549 ArrayList receivers = new ArrayList();
12550 receivers.add(bf);
12551
12552 int N = allSticky.size();
12553 for (int i=0; i<N; i++) {
12554 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012555 BroadcastQueue queue = broadcastQueueForIntent(intent);
12556 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012557 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012558 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012559 queue.enqueueParallelBroadcastLocked(r);
12560 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012561 }
12562 }
12563
12564 return sticky;
12565 }
12566 }
12567
12568 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012569 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012570
Christopher Tatef46723b2012-01-26 14:19:24 -080012571 final long origId = Binder.clearCallingIdentity();
12572 try {
12573 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012574
Christopher Tatef46723b2012-01-26 14:19:24 -080012575 synchronized(this) {
12576 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012577 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012578 if (rl != null) {
12579 if (rl.curBroadcast != null) {
12580 BroadcastRecord r = rl.curBroadcast;
12581 final boolean doNext = finishReceiverLocked(
12582 receiver.asBinder(), r.resultCode, r.resultData,
12583 r.resultExtras, r.resultAbort, true);
12584 if (doNext) {
12585 doTrim = true;
12586 r.queue.processNextBroadcast(false);
12587 }
12588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589
Christopher Tatef46723b2012-01-26 14:19:24 -080012590 if (rl.app != null) {
12591 rl.app.receivers.remove(rl);
12592 }
12593 removeReceiverLocked(rl);
12594 if (rl.linkedToDeath) {
12595 rl.linkedToDeath = false;
12596 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012598 }
12599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012600
Christopher Tatef46723b2012-01-26 14:19:24 -080012601 // If we actually concluded any broadcasts, we might now be able
12602 // to trim the recipients' apps from our working set
12603 if (doTrim) {
12604 trimApplications();
12605 return;
12606 }
12607
12608 } finally {
12609 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012611 }
12612
12613 void removeReceiverLocked(ReceiverList rl) {
12614 mRegisteredReceivers.remove(rl.receiver.asBinder());
12615 int N = rl.size();
12616 for (int i=0; i<N; i++) {
12617 mReceiverResolver.removeFilter(rl.get(i));
12618 }
12619 }
12620
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012621 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12622 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12623 ProcessRecord r = mLruProcesses.get(i);
12624 if (r.thread != null) {
12625 try {
12626 r.thread.dispatchPackageBroadcast(cmd, packages);
12627 } catch (RemoteException ex) {
12628 }
12629 }
12630 }
12631 }
12632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012633 private final int broadcastIntentLocked(ProcessRecord callerApp,
12634 String callerPackage, Intent intent, String resolvedType,
12635 IIntentReceiver resultTo, int resultCode, String resultData,
12636 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012637 boolean ordered, boolean sticky, int callingPid, int callingUid,
12638 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012639 intent = new Intent(intent);
12640
Dianne Hackborne7f97212011-02-24 14:40:20 -080012641 // By default broadcasts do not go to stopped apps.
12642 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12643
Joe Onorato8a9b2202010-02-26 18:56:32 -080012644 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012646 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012647 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012648 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012649 }
12650
12651 // Handle special intents: if this broadcast is from the package
12652 // manager about a package being removed, we need to remove all of
12653 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012654 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012655 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012656 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12657 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012658 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012659 || uidRemoved) {
12660 if (checkComponentPermission(
12661 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012662 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663 == PackageManager.PERMISSION_GRANTED) {
12664 if (uidRemoved) {
12665 final Bundle intentExtras = intent.getExtras();
12666 final int uid = intentExtras != null
12667 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12668 if (uid >= 0) {
12669 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12670 synchronized (bs) {
12671 bs.removeUidStatsLocked(uid);
12672 }
12673 }
12674 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012675 // If resources are unvailble just force stop all
12676 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012677 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012678 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12679 if (list != null && (list.length > 0)) {
12680 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012681 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012682 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012683 sendPackageBroadcastLocked(
12684 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012685 }
12686 } else {
12687 Uri data = intent.getData();
12688 String ssp;
12689 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12690 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12691 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012692 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12693 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012694 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012695 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012696 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12697 new String[] {ssp});
12698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012699 }
12700 }
12701 }
12702 } else {
12703 String msg = "Permission Denial: " + intent.getAction()
12704 + " broadcast from " + callerPackage + " (pid=" + callingPid
12705 + ", uid=" + callingUid + ")"
12706 + " requires "
12707 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012708 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012709 throw new SecurityException(msg);
12710 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012711
12712 // Special case for adding a package: by default turn on compatibility
12713 // mode.
12714 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012715 Uri data = intent.getData();
12716 String ssp;
12717 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12718 mCompatModePackages.handlePackageAddedLocked(ssp,
12719 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 }
12722
12723 /*
12724 * If this is the time zone changed action, queue up a message that will reset the timezone
12725 * of all currently running processes. This message will get queued up before the broadcast
12726 * happens.
12727 */
12728 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12729 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12730 }
12731
Robert Greenwalt03595d02010-11-02 14:08:23 -070012732 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12733 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12734 }
12735
Robert Greenwalt434203a2010-10-11 16:00:27 -070012736 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12737 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12738 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12739 }
12740
Dianne Hackborn854060af2009-07-09 18:14:31 -070012741 /*
12742 * Prevent non-system code (defined here to be non-persistent
12743 * processes) from sending protected broadcasts.
12744 */
12745 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12746 || callingUid == Process.SHELL_UID || callingUid == 0) {
12747 // Always okay.
12748 } else if (callerApp == null || !callerApp.persistent) {
12749 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012750 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012751 intent.getAction())) {
12752 String msg = "Permission Denial: not allowed to send broadcast "
12753 + intent.getAction() + " from pid="
12754 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012755 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012756 throw new SecurityException(msg);
12757 }
12758 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012759 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012760 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012761 }
12762 }
12763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012764 // Add to the sticky list if requested.
12765 if (sticky) {
12766 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12767 callingPid, callingUid)
12768 != PackageManager.PERMISSION_GRANTED) {
12769 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12770 + callingPid + ", uid=" + callingUid
12771 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012772 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773 throw new SecurityException(msg);
12774 }
12775 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012776 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012777 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012778 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779 }
12780 if (intent.getComponent() != null) {
12781 throw new SecurityException(
12782 "Sticky broadcasts can't target a specific component");
12783 }
12784 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12785 if (list == null) {
12786 list = new ArrayList<Intent>();
12787 mStickyBroadcasts.put(intent.getAction(), list);
12788 }
12789 int N = list.size();
12790 int i;
12791 for (i=0; i<N; i++) {
12792 if (intent.filterEquals(list.get(i))) {
12793 // This sticky already exists, replace it.
12794 list.set(i, new Intent(intent));
12795 break;
12796 }
12797 }
12798 if (i >= N) {
12799 list.add(new Intent(intent));
12800 }
12801 }
12802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 // Figure out who all will receive this broadcast.
12804 List receivers = null;
12805 List<BroadcastFilter> registeredReceivers = null;
12806 try {
12807 if (intent.getComponent() != null) {
12808 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012809 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012810 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012811 if (ai != null) {
12812 receivers = new ArrayList();
12813 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012814 if (isSingleton(ai.processName, ai.applicationInfo)) {
12815 ri.activityInfo = getActivityInfoForUser(ai, 0);
12816 } else {
12817 ri.activityInfo = getActivityInfoForUser(ai, userId);
12818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 receivers.add(ri);
12820 }
12821 } else {
12822 // Need to resolve the intent to interested receivers...
12823 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12824 == 0) {
12825 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012826 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012827 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012828 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012829 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12830 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012831 }
12832 } catch (RemoteException ex) {
12833 // pm is in same process, this will never happen.
12834 }
12835
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012836 final boolean replacePending =
12837 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12838
Joe Onorato8a9b2202010-02-26 18:56:32 -080012839 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012840 + " replacePending=" + replacePending);
12841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12843 if (!ordered && NR > 0) {
12844 // If we are not serializing this broadcast, then send the
12845 // registered receivers separately so they don't wait for the
12846 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012847 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12848 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012849 callerPackage, callingPid, callingUid, requiredPermission,
12850 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012851 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012852 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012853 TAG, "Enqueueing parallel broadcast " + r);
12854 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012855 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012856 queue.enqueueParallelBroadcastLocked(r);
12857 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859 registeredReceivers = null;
12860 NR = 0;
12861 }
12862
12863 // Merge into one list.
12864 int ir = 0;
12865 if (receivers != null) {
12866 // A special case for PACKAGE_ADDED: do not allow the package
12867 // being added to see this broadcast. This prevents them from
12868 // using this as a back door to get run as soon as they are
12869 // installed. Maybe in the future we want to have a special install
12870 // broadcast or such for apps, but we'd like to deliberately make
12871 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012872 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012873 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12874 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12875 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012876 Uri data = intent.getData();
12877 if (data != null) {
12878 String pkgName = data.getSchemeSpecificPart();
12879 if (pkgName != null) {
12880 skipPackages = new String[] { pkgName };
12881 }
12882 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012883 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012884 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012885 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012886 if (skipPackages != null && (skipPackages.length > 0)) {
12887 for (String skipPackage : skipPackages) {
12888 if (skipPackage != null) {
12889 int NT = receivers.size();
12890 for (int it=0; it<NT; it++) {
12891 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12892 if (curt.activityInfo.packageName.equals(skipPackage)) {
12893 receivers.remove(it);
12894 it--;
12895 NT--;
12896 }
12897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012898 }
12899 }
12900 }
12901
12902 int NT = receivers != null ? receivers.size() : 0;
12903 int it = 0;
12904 ResolveInfo curt = null;
12905 BroadcastFilter curr = null;
12906 while (it < NT && ir < NR) {
12907 if (curt == null) {
12908 curt = (ResolveInfo)receivers.get(it);
12909 }
12910 if (curr == null) {
12911 curr = registeredReceivers.get(ir);
12912 }
12913 if (curr.getPriority() >= curt.priority) {
12914 // Insert this broadcast record into the final list.
12915 receivers.add(it, curr);
12916 ir++;
12917 curr = null;
12918 it++;
12919 NT++;
12920 } else {
12921 // Skip to the next ResolveInfo in the final list.
12922 it++;
12923 curt = null;
12924 }
12925 }
12926 }
12927 while (ir < NR) {
12928 if (receivers == null) {
12929 receivers = new ArrayList();
12930 }
12931 receivers.add(registeredReceivers.get(ir));
12932 ir++;
12933 }
12934
12935 if ((receivers != null && receivers.size() > 0)
12936 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012937 BroadcastQueue queue = broadcastQueueForIntent(intent);
12938 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012940 receivers, resultTo, resultCode, resultData, map, ordered,
12941 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012942 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012943 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012944 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012945 if (DEBUG_BROADCAST) {
12946 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012947 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012948 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012949 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012950 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012951 queue.enqueueOrderedBroadcastLocked(r);
12952 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012954 }
12955
Dianne Hackborna4972e92012-03-14 10:38:05 -070012956 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012957 }
12958
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012959 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012960 // Refuse possible leaked file descriptors
12961 if (intent != null && intent.hasFileDescriptors() == true) {
12962 throw new IllegalArgumentException("File descriptors passed in Intent");
12963 }
12964
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012965 int flags = intent.getFlags();
12966
12967 if (!mProcessesReady) {
12968 // if the caller really truly claims to know what they're doing, go
12969 // ahead and allow the broadcast without launching any receivers
12970 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12971 intent = new Intent(intent);
12972 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12973 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12974 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12975 + " before boot completion");
12976 throw new IllegalStateException("Cannot broadcast before boot completed");
12977 }
12978 }
12979
12980 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12981 throw new IllegalArgumentException(
12982 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12983 }
12984
12985 return intent;
12986 }
12987
12988 public final int broadcastIntent(IApplicationThread caller,
12989 Intent intent, String resolvedType, IIntentReceiver resultTo,
12990 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012991 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012992 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012994 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012996 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12997 final int callingPid = Binder.getCallingPid();
12998 final int callingUid = Binder.getCallingUid();
12999 final long origId = Binder.clearCallingIdentity();
13000 int res = broadcastIntentLocked(callerApp,
13001 callerApp != null ? callerApp.info.packageName : null,
13002 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013003 resultCode, resultData, map, requiredPermission, serialized, sticky,
13004 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013005 Binder.restoreCallingIdentity(origId);
13006 return res;
13007 }
13008 }
13009
13010 int broadcastIntentInPackage(String packageName, int uid,
13011 Intent intent, String resolvedType, IIntentReceiver resultTo,
13012 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013013 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013014 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013015 intent = verifyBroadcastLocked(intent);
13016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013017 final long origId = Binder.clearCallingIdentity();
13018 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13019 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013020 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013021 Binder.restoreCallingIdentity(origId);
13022 return res;
13023 }
13024 }
13025
Amith Yamasani742a6712011-05-04 14:49:28 -070013026 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13027 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 // Refuse possible leaked file descriptors
13029 if (intent != null && intent.hasFileDescriptors() == true) {
13030 throw new IllegalArgumentException("File descriptors passed in Intent");
13031 }
13032
13033 synchronized(this) {
13034 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13035 != PackageManager.PERMISSION_GRANTED) {
13036 String msg = "Permission Denial: unbroadcastIntent() from pid="
13037 + Binder.getCallingPid()
13038 + ", uid=" + Binder.getCallingUid()
13039 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013040 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013041 throw new SecurityException(msg);
13042 }
13043 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13044 if (list != null) {
13045 int N = list.size();
13046 int i;
13047 for (i=0; i<N; i++) {
13048 if (intent.filterEquals(list.get(i))) {
13049 list.remove(i);
13050 break;
13051 }
13052 }
13053 }
13054 }
13055 }
13056
13057 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13058 String resultData, Bundle resultExtras, boolean resultAbort,
13059 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013060 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13061 if (r == null) {
13062 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 return false;
13064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065
Christopher Tatef46723b2012-01-26 14:19:24 -080013066 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13067 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013068 }
13069
13070 public void finishReceiver(IBinder who, int resultCode, String resultData,
13071 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013072 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013073
13074 // Refuse possible leaked file descriptors
13075 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13076 throw new IllegalArgumentException("File descriptors passed in Bundle");
13077 }
13078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013080 try {
13081 boolean doNext = false;
13082 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013083
Christopher Tatef46723b2012-01-26 14:19:24 -080013084 synchronized(this) {
13085 r = broadcastRecordForReceiverLocked(who);
13086 if (r != null) {
13087 doNext = r.queue.finishReceiverLocked(r, resultCode,
13088 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013090 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013091
Christopher Tatef46723b2012-01-26 14:19:24 -080013092 if (doNext) {
13093 r.queue.processNextBroadcast(false);
13094 }
13095 trimApplications();
13096 } finally {
13097 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013101 // =========================================================
13102 // INSTRUMENTATION
13103 // =========================================================
13104
13105 public boolean startInstrumentation(ComponentName className,
13106 String profileFile, int flags, Bundle arguments,
13107 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013108 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013109 // Refuse possible leaked file descriptors
13110 if (arguments != null && arguments.hasFileDescriptors()) {
13111 throw new IllegalArgumentException("File descriptors passed in Bundle");
13112 }
13113
13114 synchronized(this) {
13115 InstrumentationInfo ii = null;
13116 ApplicationInfo ai = null;
13117 try {
13118 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013119 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013120 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013121 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 } catch (PackageManager.NameNotFoundException e) {
13123 }
13124 if (ii == null) {
13125 reportStartInstrumentationFailure(watcher, className,
13126 "Unable to find instrumentation info for: " + className);
13127 return false;
13128 }
13129 if (ai == null) {
13130 reportStartInstrumentationFailure(watcher, className,
13131 "Unable to find instrumentation target package: " + ii.targetPackage);
13132 return false;
13133 }
13134
13135 int match = mContext.getPackageManager().checkSignatures(
13136 ii.targetPackage, ii.packageName);
13137 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13138 String msg = "Permission Denial: starting instrumentation "
13139 + className + " from pid="
13140 + Binder.getCallingPid()
13141 + ", uid=" + Binder.getCallingPid()
13142 + " not allowed because package " + ii.packageName
13143 + " does not have a signature matching the target "
13144 + ii.targetPackage;
13145 reportStartInstrumentationFailure(watcher, className, msg);
13146 throw new SecurityException(msg);
13147 }
13148
Amith Yamasani483f3b02012-03-13 16:08:00 -070013149 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013150 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013151 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013152 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013153 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013154 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013155 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013156 app.instrumentationProfileFile = profileFile;
13157 app.instrumentationArguments = arguments;
13158 app.instrumentationWatcher = watcher;
13159 app.instrumentationResultClass = className;
13160 Binder.restoreCallingIdentity(origId);
13161 }
13162
13163 return true;
13164 }
13165
13166 /**
13167 * Report errors that occur while attempting to start Instrumentation. Always writes the
13168 * error to the logs, but if somebody is watching, send the report there too. This enables
13169 * the "am" command to report errors with more information.
13170 *
13171 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13172 * @param cn The component name of the instrumentation.
13173 * @param report The error report.
13174 */
13175 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13176 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013177 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013178 try {
13179 if (watcher != null) {
13180 Bundle results = new Bundle();
13181 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13182 results.putString("Error", report);
13183 watcher.instrumentationStatus(cn, -1, results);
13184 }
13185 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013186 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013187 }
13188 }
13189
13190 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13191 if (app.instrumentationWatcher != null) {
13192 try {
13193 // NOTE: IInstrumentationWatcher *must* be oneway here
13194 app.instrumentationWatcher.instrumentationFinished(
13195 app.instrumentationClass,
13196 resultCode,
13197 results);
13198 } catch (RemoteException e) {
13199 }
13200 }
13201 app.instrumentationWatcher = null;
13202 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013203 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013204 app.instrumentationProfileFile = null;
13205 app.instrumentationArguments = null;
13206
Amith Yamasani483f3b02012-03-13 16:08:00 -070013207 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013208 }
13209
13210 public void finishInstrumentation(IApplicationThread target,
13211 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013212 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 // Refuse possible leaked file descriptors
13214 if (results != null && results.hasFileDescriptors()) {
13215 throw new IllegalArgumentException("File descriptors passed in Intent");
13216 }
13217
13218 synchronized(this) {
13219 ProcessRecord app = getRecordForAppLocked(target);
13220 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013221 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013222 return;
13223 }
13224 final long origId = Binder.clearCallingIdentity();
13225 finishInstrumentationLocked(app, resultCode, results);
13226 Binder.restoreCallingIdentity(origId);
13227 }
13228 }
13229
13230 // =========================================================
13231 // CONFIGURATION
13232 // =========================================================
13233
13234 public ConfigurationInfo getDeviceConfigurationInfo() {
13235 ConfigurationInfo config = new ConfigurationInfo();
13236 synchronized (this) {
13237 config.reqTouchScreen = mConfiguration.touchscreen;
13238 config.reqKeyboardType = mConfiguration.keyboard;
13239 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013240 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13241 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013242 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13243 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013244 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13245 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013246 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13247 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013248 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 }
13250 return config;
13251 }
13252
13253 public Configuration getConfiguration() {
13254 Configuration ci;
13255 synchronized(this) {
13256 ci = new Configuration(mConfiguration);
13257 }
13258 return ci;
13259 }
13260
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013261 public void updatePersistentConfiguration(Configuration values) {
13262 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13263 "updateConfiguration()");
13264 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13265 "updateConfiguration()");
13266 if (values == null) {
13267 throw new NullPointerException("Configuration must not be null");
13268 }
13269
13270 synchronized(this) {
13271 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013272 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013273 Binder.restoreCallingIdentity(origId);
13274 }
13275 }
13276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013277 public void updateConfiguration(Configuration values) {
13278 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13279 "updateConfiguration()");
13280
13281 synchronized(this) {
13282 if (values == null && mWindowManager != null) {
13283 // sentinel: fetch the current configuration from the window manager
13284 values = mWindowManager.computeNewConfiguration();
13285 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013286
13287 if (mWindowManager != null) {
13288 mProcessList.applyDisplaySize(mWindowManager);
13289 }
13290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013291 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013292 if (values != null) {
13293 Settings.System.clearConfiguration(values);
13294 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013295 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013296 Binder.restoreCallingIdentity(origId);
13297 }
13298 }
13299
13300 /**
13301 * Do either or both things: (1) change the current configuration, and (2)
13302 * make sure the given activity is running with the (now) current
13303 * configuration. Returns true if the activity has been left running, or
13304 * false if <var>starting</var> is being destroyed to match the new
13305 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013306 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013307 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013308 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013309 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013310 // do nothing if we are headless
13311 if (mHeadless) return true;
13312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013313 int changes = 0;
13314
13315 boolean kept = true;
13316
13317 if (values != null) {
13318 Configuration newConfig = new Configuration(mConfiguration);
13319 changes = newConfig.updateFrom(values);
13320 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013321 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013322 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013323 }
13324
Doug Zongker2bec3d42009-12-04 12:52:44 -080013325 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013326
Dianne Hackborn813075a62011-11-14 17:45:19 -080013327 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013328 saveLocaleLocked(values.locale,
13329 !values.locale.equals(mConfiguration.locale),
13330 values.userSetLocale);
13331 }
13332
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013333 mConfigurationSeq++;
13334 if (mConfigurationSeq <= 0) {
13335 mConfigurationSeq = 1;
13336 }
13337 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013339 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013340
13341 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013342
13343 // TODO: If our config changes, should we auto dismiss any currently
13344 // showing dialogs?
13345 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013346
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013347 AttributeCache ac = AttributeCache.instance();
13348 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013349 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013351
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013352 // Make sure all resources in our process are updated
13353 // right now, so that anyone who is going to retrieve
13354 // resource values after we return will be sure to get
13355 // the new ones. This is especially important during
13356 // boot, where the first config change needs to guarantee
13357 // all resources have that config before following boot
13358 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013359 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013360
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013361 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013362 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013363 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013364 mHandler.sendMessage(msg);
13365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013366
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013367 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13368 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013369 try {
13370 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013371 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013372 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013373 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 }
13375 } catch (Exception e) {
13376 }
13377 }
13378 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013379 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13380 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013381 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013382 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013383 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13384 broadcastIntentLocked(null, null,
13385 new Intent(Intent.ACTION_LOCALE_CHANGED),
13386 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013387 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 }
13390 }
13391
13392 if (changes != 0 && starting == null) {
13393 // If the configuration changed, and the caller is not already
13394 // in the process of starting an activity, then find the top
13395 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013396 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013397 }
13398
13399 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013400 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013401 // And we need to make sure at this point that all other activities
13402 // are made visible with the correct configuration.
13403 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404 }
13405
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013406 if (values != null && mWindowManager != null) {
13407 mWindowManager.setNewConfiguration(mConfiguration);
13408 }
13409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013410 return kept;
13411 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013412
13413 /**
13414 * Decide based on the configuration whether we should shouw the ANR,
13415 * crash, etc dialogs. The idea is that if there is no affordnace to
13416 * press the on-screen buttons, we shouldn't show the dialog.
13417 *
13418 * A thought: SystemUI might also want to get told about this, the Power
13419 * dialog / global actions also might want different behaviors.
13420 */
13421 private static final boolean shouldShowDialogs(Configuration config) {
13422 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13423 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013425
13426 /**
13427 * Save the locale. You must be inside a synchronized (this) block.
13428 */
13429 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13430 if(isDiff) {
13431 SystemProperties.set("user.language", l.getLanguage());
13432 SystemProperties.set("user.region", l.getCountry());
13433 }
13434
13435 if(isPersist) {
13436 SystemProperties.set("persist.sys.language", l.getLanguage());
13437 SystemProperties.set("persist.sys.country", l.getCountry());
13438 SystemProperties.set("persist.sys.localevar", l.getVariant());
13439 }
13440 }
13441
Adam Powelldd8fab22012-03-22 17:47:27 -070013442 @Override
13443 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13444 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013445 return srec != null && srec.task.affinity != null &&
13446 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013447 }
13448
13449 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13450 Intent resultData) {
13451 ComponentName dest = destIntent.getComponent();
13452
13453 synchronized (this) {
13454 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013455 if (srec == null) {
13456 return false;
13457 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013458 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13459 final int start = history.indexOf(srec);
13460 if (start < 0) {
13461 // Current activity is not in history stack; do nothing.
13462 return false;
13463 }
13464 int finishTo = start - 1;
13465 ActivityRecord parent = null;
13466 boolean foundParentInTask = false;
13467 if (dest != null) {
13468 TaskRecord tr = srec.task;
13469 for (int i = start - 1; i >= 0; i--) {
13470 ActivityRecord r = history.get(i);
13471 if (tr != r.task) {
13472 // Couldn't find parent in the same task; stop at the one above this.
13473 // (Root of current task; in-app "home" behavior)
13474 // Always at least finish the current activity.
13475 finishTo = Math.min(start - 1, i + 1);
13476 parent = history.get(finishTo);
13477 break;
13478 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13479 r.info.name.equals(dest.getClassName())) {
13480 finishTo = i;
13481 parent = r;
13482 foundParentInTask = true;
13483 break;
13484 }
13485 }
13486 }
13487
13488 if (mController != null) {
13489 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13490 if (next != null) {
13491 // ask watcher if this is allowed
13492 boolean resumeOK = true;
13493 try {
13494 resumeOK = mController.activityResuming(next.packageName);
13495 } catch (RemoteException e) {
13496 mController = null;
13497 }
13498
13499 if (!resumeOK) {
13500 return false;
13501 }
13502 }
13503 }
13504 final long origId = Binder.clearCallingIdentity();
13505 for (int i = start; i > finishTo; i--) {
13506 ActivityRecord r = history.get(i);
13507 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13508 "navigate-up");
13509 // Only return the supplied result for the first activity finished
13510 resultCode = Activity.RESULT_CANCELED;
13511 resultData = null;
13512 }
13513
13514 if (parent != null && foundParentInTask) {
13515 final int parentLaunchMode = parent.info.launchMode;
13516 final int destIntentFlags = destIntent.getFlags();
13517 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13518 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13519 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13520 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070013521 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070013522 } else {
13523 try {
13524 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13525 destIntent.getComponent(), 0, UserId.getCallingUserId());
13526 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13527 null, aInfo, parent.appToken, null,
13528 0, -1, parent.launchedFromUid, 0, null, true, null);
13529 foundParentInTask = res == ActivityManager.START_SUCCESS;
13530 } catch (RemoteException e) {
13531 foundParentInTask = false;
13532 }
13533 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13534 resultData, "navigate-up");
13535 }
13536 }
13537 Binder.restoreCallingIdentity(origId);
13538 return foundParentInTask;
13539 }
13540 }
13541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013542 // =========================================================
13543 // LIFETIME MANAGEMENT
13544 // =========================================================
13545
Christopher Tatef46723b2012-01-26 14:19:24 -080013546 // Returns which broadcast queue the app is the current [or imminent] receiver
13547 // on, or 'null' if the app is not an active broadcast recipient.
13548 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13549 BroadcastRecord r = app.curReceiver;
13550 if (r != null) {
13551 return r.queue;
13552 }
13553
13554 // It's not the current receiver, but it might be starting up to become one
13555 synchronized (this) {
13556 for (BroadcastQueue queue : mBroadcastQueues) {
13557 r = queue.mPendingBroadcast;
13558 if (r != null && r.curApp == app) {
13559 // found it; report which queue it's in
13560 return queue;
13561 }
13562 }
13563 }
13564
13565 return null;
13566 }
13567
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013568 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013569 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013570 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013571 // This adjustment has already been computed. If we are calling
13572 // from the top, we may have already computed our adjustment with
13573 // an earlier hidden adjustment that isn't really for us... if
13574 // so, use the new hidden adjustment.
13575 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013576 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013577 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013578 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013579 }
13580
13581 if (app.thread == null) {
13582 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013583 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013584 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013585 }
13586
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013587 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13588 app.adjSource = null;
13589 app.adjTarget = null;
13590 app.empty = false;
13591 app.hidden = false;
13592
13593 final int activitiesSize = app.activities.size();
13594
Dianne Hackborn7d608422011-08-07 16:24:18 -070013595 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013596 // The max adjustment doesn't allow this app to be anything
13597 // below foreground, so it is not worth doing work for it.
13598 app.adjType = "fixed";
13599 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013600 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013601 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013602 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013603 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013604 // System process can do UI, and when they do we want to have
13605 // them trim their memory after the user leaves the UI. To
13606 // facilitate this, here we need to determine whether or not it
13607 // is currently showing UI.
13608 app.systemNoUi = true;
13609 if (app == TOP_APP) {
13610 app.systemNoUi = false;
13611 } else if (activitiesSize > 0) {
13612 for (int j = 0; j < activitiesSize; j++) {
13613 final ActivityRecord r = app.activities.get(j);
13614 if (r.visible) {
13615 app.systemNoUi = false;
13616 break;
13617 }
13618 }
13619 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013620 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013621 }
13622
13623 final boolean hadForegroundActivities = app.foregroundActivities;
13624
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013625 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013626 app.keeping = false;
13627 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013628
The Android Open Source Project4df24232009-03-05 14:34:35 -080013629 // Determine the importance of the process, starting with most
13630 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013631 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013632 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013633 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013634 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013635 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013636 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013637 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013638 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013639 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013640 } else if (app.instrumentationClass != null) {
13641 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013642 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013643 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013644 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013645 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013646 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013647 // counts as being in the foreground for OOM killer purposes.
13648 // It's placed in a sched group based on the nature of the
13649 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013650 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013651 schedGroup = (queue == mFgBroadcastQueue)
13652 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013653 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013654 } else if (app.executingServices.size() > 0) {
13655 // An app that is currently executing a service callback also
13656 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013657 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013658 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013659 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013660 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013661 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013662 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013663 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013664 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013665 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013666 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013667 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013668 // A very not-needed process. If this is lower in the lru list,
13669 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013670 adj = hiddenAdj;
13671 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013672 app.hidden = true;
13673 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013674 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013675 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013676
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013677 boolean hasStoppingActivities = false;
13678
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013679 // Examine all activities if not already foreground.
13680 if (!app.foregroundActivities && activitiesSize > 0) {
13681 for (int j = 0; j < activitiesSize; j++) {
13682 final ActivityRecord r = app.activities.get(j);
13683 if (r.visible) {
13684 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013685 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13686 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013687 app.adjType = "visible";
13688 }
13689 schedGroup = Process.THREAD_GROUP_DEFAULT;
13690 app.hidden = false;
13691 app.foregroundActivities = true;
13692 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013693 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013694 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13695 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013696 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013697 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013698 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013699 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013700 } else if (r.state == ActivityState.STOPPING) {
13701 // We will apply the actual adjustment later, because
13702 // we want to allow this process to immediately go through
13703 // any memory trimming that is in effect.
13704 app.hidden = false;
13705 app.foregroundActivities = true;
13706 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013707 }
13708 }
13709 }
13710
Dianne Hackborn7d608422011-08-07 16:24:18 -070013711 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013712 if (app.foregroundServices) {
13713 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013714 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013715 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013716 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013717 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013718 } else if (app.forcingToForeground != null) {
13719 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013720 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013721 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013722 app.adjType = "force-foreground";
13723 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013724 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013725 }
13726 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013727
Dianne Hackborn7d608422011-08-07 16:24:18 -070013728 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013729 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013730 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013731 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013732 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013733 app.adjType = "heavy";
13734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013735
Dianne Hackborn7d608422011-08-07 16:24:18 -070013736 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013737 // This process is hosting what we currently consider to be the
13738 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013739 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013740 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013741 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013742 app.adjType = "home";
13743 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013744
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013745 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13746 && app.activities.size() > 0) {
13747 // This was the previous process that showed UI to the user.
13748 // We want to try to keep it around more aggressively, to give
13749 // a good experience around switching between two apps.
13750 adj = ProcessList.PREVIOUS_APP_ADJ;
13751 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13752 app.hidden = false;
13753 app.adjType = "previous";
13754 }
13755
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013756 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13757 + " reason=" + app.adjType);
13758
The Android Open Source Project4df24232009-03-05 14:34:35 -080013759 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013760 // there are applications dependent on our services or providers, but
13761 // this gives us a baseline and makes sure we don't get into an
13762 // infinite recursion.
13763 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013764 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013765
Christopher Tate6fa95972009-06-05 18:43:55 -070013766 if (mBackupTarget != null && app == mBackupTarget.app) {
13767 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013768 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013769 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013770 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013771 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013772 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013773 }
13774 }
13775
Dianne Hackborn7d608422011-08-07 16:24:18 -070013776 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013777 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013778 final long now = SystemClock.uptimeMillis();
13779 // This process is more important if the top activity is
13780 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013781 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013782 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013783 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013784 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013785 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013786 // If this process has shown some UI, let it immediately
13787 // go to the LRU list because it may be pretty heavy with
13788 // UI stuff. We'll tag it with a label just to help
13789 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013790 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013791 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013792 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013793 } else {
13794 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13795 // This service has seen some activity within
13796 // recent memory, so we will keep its process ahead
13797 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013798 if (adj > ProcessList.SERVICE_ADJ) {
13799 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013800 app.adjType = "started-services";
13801 app.hidden = false;
13802 }
13803 }
13804 // If we have let the service slide into the background
13805 // state, still have some text describing what it is doing
13806 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013807 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013808 app.adjType = "started-bg-services";
13809 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013810 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013811 // Don't kill this process because it is doing work; it
13812 // has said it is doing work.
13813 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013814 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013815 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013816 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013817 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013818 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013819 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013820 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013821 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013822 // XXX should compute this based on the max of
13823 // all connected clients.
13824 ConnectionRecord cr = clist.get(i);
13825 if (cr.binding.client == app) {
13826 // Binding to ourself is not interesting.
13827 continue;
13828 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013829 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013830 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013831 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013832 int myHiddenAdj = hiddenAdj;
13833 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013834 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013835 myHiddenAdj = client.hiddenAdj;
13836 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013837 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013838 }
13839 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013840 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013841 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013842 String adjType = null;
13843 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13844 // Not doing bind OOM management, so treat
13845 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013846 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013847 // If this process has shown some UI, let it immediately
13848 // go to the LRU list because it may be pretty heavy with
13849 // UI stuff. We'll tag it with a label just to help
13850 // debug and understand what is going on.
13851 if (adj > clientAdj) {
13852 adjType = "bound-bg-ui-services";
13853 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013854 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013855 clientAdj = adj;
13856 } else {
13857 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13858 // This service has not seen activity within
13859 // recent memory, so allow it to drop to the
13860 // LRU list if there is no other reason to keep
13861 // it around. We'll also tag it with a label just
13862 // to help debug and undertand what is going on.
13863 if (adj > clientAdj) {
13864 adjType = "bound-bg-services";
13865 }
13866 clientAdj = adj;
13867 }
13868 }
13869 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013870 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013871 // If this process has recently shown UI, and
13872 // the process that is binding to it is less
13873 // important than being visible, then we don't
13874 // care about the binding as much as we care
13875 // about letting this process get into the LRU
13876 // list to be killed and restarted if needed for
13877 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013878 if (app.hasShownUi && app != mHomeProcess
13879 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013880 adjType = "bound-bg-ui-services";
13881 } else {
13882 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13883 |Context.BIND_IMPORTANT)) != 0) {
13884 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013885 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13886 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13887 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13888 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13889 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013890 adj = clientAdj;
13891 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013892 app.pendingUiClean = true;
13893 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13894 adj = ProcessList.VISIBLE_APP_ADJ;
13895 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013896 }
13897 if (!client.hidden) {
13898 app.hidden = false;
13899 }
13900 if (client.keeping) {
13901 app.keeping = true;
13902 }
13903 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013904 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013905 }
13906 if (adjType != null) {
13907 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013908 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13909 .REASON_SERVICE_IN_USE;
13910 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013911 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013912 app.adjTarget = s.name;
13913 }
13914 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13915 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13916 schedGroup = Process.THREAD_GROUP_DEFAULT;
13917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013918 }
13919 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013920 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13921 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013922 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013923 (a.visible || a.state == ActivityState.RESUMED
13924 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013925 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013926 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13927 schedGroup = Process.THREAD_GROUP_DEFAULT;
13928 }
13929 app.hidden = false;
13930 app.adjType = "service";
13931 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13932 .REASON_SERVICE_IN_USE;
13933 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013934 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013935 app.adjTarget = s.name;
13936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013938 }
13939 }
13940 }
13941 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013942
Dianne Hackborn287952c2010-09-22 22:34:31 -070013943 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013944 // would like to avoid killing it unless it would prevent the current
13945 // application from running. By default we put the process in
13946 // with the rest of the background processes; as we scan through
13947 // its services we may bump it up from there.
13948 if (adj > hiddenAdj) {
13949 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013950 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013951 app.adjType = "bg-services";
13952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013953 }
13954
Dianne Hackborn7d608422011-08-07 16:24:18 -070013955 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013956 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013957 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013958 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013959 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013960 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013961 if (cpr.clients.size() != 0) {
13962 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013963 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013964 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013965 if (client == app) {
13966 // Being our own client is not interesting.
13967 continue;
13968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 int myHiddenAdj = hiddenAdj;
13970 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013971 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013972 myHiddenAdj = client.hiddenAdj;
13973 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013974 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013975 }
13976 }
13977 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013978 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013979 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013980 if (app.hasShownUi && app != mHomeProcess
13981 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013982 app.adjType = "bg-ui-provider";
13983 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013984 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13985 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013986 app.adjType = "provider";
13987 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013988 if (!client.hidden) {
13989 app.hidden = false;
13990 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013991 if (client.keeping) {
13992 app.keeping = true;
13993 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013994 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13995 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013996 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013997 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013998 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013999 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014000 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14001 schedGroup = Process.THREAD_GROUP_DEFAULT;
14002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014003 }
14004 }
14005 // If the provider has external (non-framework) process
14006 // dependencies, ensure that its adjustment is at least
14007 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080014008 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014009 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14010 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014011 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014012 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014013 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014014 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014015 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014016 }
14017 }
14018 }
14019 }
14020
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014021 if (adj == ProcessList.SERVICE_ADJ) {
14022 if (doingAll) {
14023 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14024 mNewNumServiceProcs++;
14025 }
14026 if (app.serviceb) {
14027 adj = ProcessList.SERVICE_B_ADJ;
14028 }
14029 } else {
14030 app.serviceb = false;
14031 }
14032
14033 app.nonStoppingAdj = adj;
14034
14035 if (hasStoppingActivities) {
14036 // Only upgrade adjustment.
14037 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14038 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14039 app.adjType = "stopping";
14040 }
14041 }
14042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014043 app.curRawAdj = adj;
14044
Joe Onorato8a9b2202010-02-26 18:56:32 -080014045 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014046 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14047 if (adj > app.maxAdj) {
14048 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014049 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014050 schedGroup = Process.THREAD_GROUP_DEFAULT;
14051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014052 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014053 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014054 app.keeping = true;
14055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014056
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014057 if (app.hasAboveClient) {
14058 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14059 // then we need to drop its adjustment to be lower than the service's
14060 // in order to honor the request. We want to drop it by one adjustment
14061 // level... but there is special meaning applied to various levels so
14062 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014063 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014064 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014065 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14066 adj = ProcessList.VISIBLE_APP_ADJ;
14067 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14068 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14069 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14070 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014071 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014072 adj++;
14073 }
14074 }
14075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014076 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014077 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014078
14079 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014080 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14081 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014082 }
14083
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014084 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014085 }
14086
14087 /**
14088 * Ask a given process to GC right now.
14089 */
14090 final void performAppGcLocked(ProcessRecord app) {
14091 try {
14092 app.lastRequestedGc = SystemClock.uptimeMillis();
14093 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014094 if (app.reportLowMemory) {
14095 app.reportLowMemory = false;
14096 app.thread.scheduleLowMemory();
14097 } else {
14098 app.thread.processInBackground();
14099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014100 }
14101 } catch (Exception e) {
14102 // whatever.
14103 }
14104 }
14105
14106 /**
14107 * Returns true if things are idle enough to perform GCs.
14108 */
Josh Bartel7f208742010-02-25 11:01:44 -060014109 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014110 boolean processingBroadcasts = false;
14111 for (BroadcastQueue q : mBroadcastQueues) {
14112 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14113 processingBroadcasts = true;
14114 }
14115 }
14116 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014117 && (mSleeping || (mMainStack.mResumedActivity != null &&
14118 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014119 }
14120
14121 /**
14122 * Perform GCs on all processes that are waiting for it, but only
14123 * if things are idle.
14124 */
14125 final void performAppGcsLocked() {
14126 final int N = mProcessesToGc.size();
14127 if (N <= 0) {
14128 return;
14129 }
Josh Bartel7f208742010-02-25 11:01:44 -060014130 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014131 while (mProcessesToGc.size() > 0) {
14132 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014133 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014134 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14135 <= SystemClock.uptimeMillis()) {
14136 // To avoid spamming the system, we will GC processes one
14137 // at a time, waiting a few seconds between each.
14138 performAppGcLocked(proc);
14139 scheduleAppGcsLocked();
14140 return;
14141 } else {
14142 // It hasn't been long enough since we last GCed this
14143 // process... put it in the list to wait for its time.
14144 addProcessToGcListLocked(proc);
14145 break;
14146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014147 }
14148 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014149
14150 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014151 }
14152 }
14153
14154 /**
14155 * If all looks good, perform GCs on all processes waiting for them.
14156 */
14157 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014158 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014159 performAppGcsLocked();
14160 return;
14161 }
14162 // Still not idle, wait some more.
14163 scheduleAppGcsLocked();
14164 }
14165
14166 /**
14167 * Schedule the execution of all pending app GCs.
14168 */
14169 final void scheduleAppGcsLocked() {
14170 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014171
14172 if (mProcessesToGc.size() > 0) {
14173 // Schedule a GC for the time to the next process.
14174 ProcessRecord proc = mProcessesToGc.get(0);
14175 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14176
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014177 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014178 long now = SystemClock.uptimeMillis();
14179 if (when < (now+GC_TIMEOUT)) {
14180 when = now + GC_TIMEOUT;
14181 }
14182 mHandler.sendMessageAtTime(msg, when);
14183 }
14184 }
14185
14186 /**
14187 * Add a process to the array of processes waiting to be GCed. Keeps the
14188 * list in sorted order by the last GC time. The process can't already be
14189 * on the list.
14190 */
14191 final void addProcessToGcListLocked(ProcessRecord proc) {
14192 boolean added = false;
14193 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14194 if (mProcessesToGc.get(i).lastRequestedGc <
14195 proc.lastRequestedGc) {
14196 added = true;
14197 mProcessesToGc.add(i+1, proc);
14198 break;
14199 }
14200 }
14201 if (!added) {
14202 mProcessesToGc.add(0, proc);
14203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014204 }
14205
14206 /**
14207 * Set up to ask a process to GC itself. This will either do it
14208 * immediately, or put it on the list of processes to gc the next
14209 * time things are idle.
14210 */
14211 final void scheduleAppGcLocked(ProcessRecord app) {
14212 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014213 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014214 return;
14215 }
14216 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014217 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014218 scheduleAppGcsLocked();
14219 }
14220 }
14221
Dianne Hackborn287952c2010-09-22 22:34:31 -070014222 final void checkExcessivePowerUsageLocked(boolean doKills) {
14223 updateCpuStatsNow();
14224
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014225 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014226 boolean doWakeKills = doKills;
14227 boolean doCpuKills = doKills;
14228 if (mLastPowerCheckRealtime == 0) {
14229 doWakeKills = false;
14230 }
14231 if (mLastPowerCheckUptime == 0) {
14232 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014233 }
14234 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014235 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014236 }
14237 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014238 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14239 final long curUptime = SystemClock.uptimeMillis();
14240 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14241 mLastPowerCheckRealtime = curRealtime;
14242 mLastPowerCheckUptime = curUptime;
14243 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14244 doWakeKills = false;
14245 }
14246 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14247 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014248 }
14249 int i = mLruProcesses.size();
14250 while (i > 0) {
14251 i--;
14252 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014253 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014254 long wtime;
14255 synchronized (stats) {
14256 wtime = stats.getProcessWakeTime(app.info.uid,
14257 app.pid, curRealtime);
14258 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014259 long wtimeUsed = wtime - app.lastWakeTime;
14260 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14261 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014262 StringBuilder sb = new StringBuilder(128);
14263 sb.append("Wake for ");
14264 app.toShortString(sb);
14265 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014266 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014267 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014268 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014269 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014270 sb.append((wtimeUsed*100)/realtimeSince);
14271 sb.append("%)");
14272 Slog.i(TAG, sb.toString());
14273 sb.setLength(0);
14274 sb.append("CPU for ");
14275 app.toShortString(sb);
14276 sb.append(": over ");
14277 TimeUtils.formatDuration(uptimeSince, sb);
14278 sb.append(" used ");
14279 TimeUtils.formatDuration(cputimeUsed, sb);
14280 sb.append(" (");
14281 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014282 sb.append("%)");
14283 Slog.i(TAG, sb.toString());
14284 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014285 // If a process has held a wake lock for more
14286 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014287 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014288 if (doWakeKills && realtimeSince > 0
14289 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14290 synchronized (stats) {
14291 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14292 realtimeSince, wtimeUsed);
14293 }
14294 Slog.w(TAG, "Excessive wake lock in " + app.processName
14295 + " (pid " + app.pid + "): held " + wtimeUsed
14296 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014297 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14298 app.processName, app.setAdj, "excessive wake lock");
14299 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014300 } else if (doCpuKills && uptimeSince > 0
14301 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14302 synchronized (stats) {
14303 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14304 uptimeSince, cputimeUsed);
14305 }
14306 Slog.w(TAG, "Excessive CPU in " + app.processName
14307 + " (pid " + app.pid + "): used " + cputimeUsed
14308 + " during " + uptimeSince);
14309 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14310 app.processName, app.setAdj, "excessive cpu");
14311 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014312 } else {
14313 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014314 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014315 }
14316 }
14317 }
14318 }
14319
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014320 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014321 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014322 app.hiddenAdj = hiddenAdj;
14323
14324 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014325 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014326 }
14327
Dianne Hackborn287952c2010-09-22 22:34:31 -070014328 final boolean wasKeeping = app.keeping;
14329
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014330 boolean success = true;
14331
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014332 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014333
Jeff Brown10e89712011-07-08 18:52:57 -070014334 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014335 if (wasKeeping && !app.keeping) {
14336 // This app is no longer something we want to keep. Note
14337 // its current wake lock time to later know to kill it if
14338 // it is not behaving well.
14339 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14340 synchronized (stats) {
14341 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14342 app.pid, SystemClock.elapsedRealtime());
14343 }
14344 app.lastCpuTime = app.curCpuTime;
14345 }
14346
14347 app.setRawAdj = app.curRawAdj;
14348 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014349
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014350 if (app.curAdj != app.setAdj) {
14351 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014352 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014353 TAG, "Set " + app.pid + " " + app.processName +
14354 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014355 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014356 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014357 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014358 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014359 }
14360 }
14361 if (app.setSchedGroup != app.curSchedGroup) {
14362 app.setSchedGroup = app.curSchedGroup;
14363 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14364 "Setting process group of " + app.processName
14365 + " to " + app.curSchedGroup);
14366 if (app.waitingToKill != null &&
14367 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14368 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14369 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14370 app.processName, app.setAdj, app.waitingToKill);
14371 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014372 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014373 } else {
14374 if (true) {
14375 long oldId = Binder.clearCallingIdentity();
14376 try {
14377 Process.setProcessGroup(app.pid, app.curSchedGroup);
14378 } catch (Exception e) {
14379 Slog.w(TAG, "Failed setting process group of " + app.pid
14380 + " to " + app.curSchedGroup);
14381 e.printStackTrace();
14382 } finally {
14383 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014384 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014385 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014386 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014387 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014388 app.thread.setSchedulingGroup(app.curSchedGroup);
14389 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014390 }
14391 }
14392 }
14393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014394 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014395 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014396 }
14397
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014398 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014399 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014400 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014401 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014402 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014403 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014404 }
14405 }
14406 return resumedActivity;
14407 }
14408
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014409 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014410 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014411 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14412 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014413 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14414 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014415
14416 mAdjSeq++;
14417
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014418 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014419 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14420 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014421 if (nowHidden != wasHidden) {
14422 // Changed to/from hidden state, so apps after it in the LRU
14423 // list may also be changed.
14424 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014425 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014426 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014427 }
14428
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014429 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014430 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014431 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14432
14433 if (false) {
14434 RuntimeException e = new RuntimeException();
14435 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014436 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014437 }
14438
14439 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014440 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014441
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014442 // Let's determine how many processes we have running vs.
14443 // how many slots we have for background processes; we may want
14444 // to put multiple processes in a slot of there are enough of
14445 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014446 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014447 int factor = (mLruProcesses.size()-4)/numSlots;
14448 if (factor < 1) factor = 1;
14449 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014450 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014451 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014452
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014453 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014454 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014455 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014456 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014457 while (i > 0) {
14458 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014459 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014460 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014461 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14462 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014463 && app.curAdj == curHiddenAdj) {
14464 step++;
14465 if (step >= factor) {
14466 step = 0;
14467 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014468 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014469 }
14470 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014471 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014472 numHidden++;
14473 if (numHidden > mProcessLimit) {
14474 Slog.i(TAG, "No longer want " + app.processName
14475 + " (pid " + app.pid + "): hidden #" + numHidden);
14476 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14477 app.processName, app.setAdj, "too many background");
14478 app.killedBackground = true;
14479 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014480 }
14481 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014482 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14483 // If this is an isolated process, and there are no
14484 // services running in it, then the process is no longer
14485 // needed. We agressively kill these because we can by
14486 // definition not re-use the same process again, and it is
14487 // good to avoid having whatever code was running in them
14488 // left sitting around after no longer needed.
14489 Slog.i(TAG, "Isolated process " + app.processName
14490 + " (pid " + app.pid + ") no longer needed");
14491 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14492 app.processName, app.setAdj, "isolated not needed");
14493 app.killedBackground = true;
14494 Process.killProcessQuiet(app.pid);
14495 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014496 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14497 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14498 && !app.killedBackground) {
14499 numTrimming++;
14500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014501 }
14502 }
14503
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014504 mNumServiceProcs = mNewNumServiceProcs;
14505
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014506 // Now determine the memory trimming level of background processes.
14507 // Unfortunately we need to start at the back of the list to do this
14508 // properly. We only do this if the number of background apps we
14509 // are managing to keep around is less than half the maximum we desire;
14510 // if we are keeping a good number around, we'll let them use whatever
14511 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014512 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014513 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014514 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014515 int minFactor = 2;
14516 if (mHomeProcess != null) minFactor++;
14517 if (mPreviousProcess != null) minFactor++;
14518 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014519 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014520 int fgTrimLevel;
14521 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14522 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14523 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14524 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14525 } else {
14526 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14527 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014528 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014529 for (i=0; i<N; i++) {
14530 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014531 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14532 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014533 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014534 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14535 try {
14536 app.thread.scheduleTrimMemory(curLevel);
14537 } catch (RemoteException e) {
14538 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014539 if (false) {
14540 // For now we won't do this; our memory trimming seems
14541 // to be good enough at this point that destroying
14542 // activities causes more harm than good.
14543 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14544 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014545 // Need to do this on its own message because the stack may not
14546 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014547 // For these apps we will also finish their activities
14548 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014549 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014550 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014551 }
14552 }
14553 app.trimMemoryLevel = curLevel;
14554 step++;
14555 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014556 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014557 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014558 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14559 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014560 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014561 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14562 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014563 break;
14564 }
14565 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014566 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014567 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014568 && app.thread != null) {
14569 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014570 app.thread.scheduleTrimMemory(
14571 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014572 } catch (RemoteException e) {
14573 }
14574 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014575 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014576 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014577 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014578 && app.pendingUiClean) {
14579 // If this application is now in the background and it
14580 // had done UI, then give it the special trim level to
14581 // have it free UI resources.
14582 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14583 if (app.trimMemoryLevel < level && app.thread != null) {
14584 try {
14585 app.thread.scheduleTrimMemory(level);
14586 } catch (RemoteException e) {
14587 }
14588 }
14589 app.pendingUiClean = false;
14590 }
14591 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014592 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014593 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014594 } catch (RemoteException e) {
14595 }
14596 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014597 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014598 }
14599 }
14600 } else {
14601 final int N = mLruProcesses.size();
14602 for (i=0; i<N; i++) {
14603 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014604 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014605 && app.pendingUiClean) {
14606 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14607 && app.thread != null) {
14608 try {
14609 app.thread.scheduleTrimMemory(
14610 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14611 } catch (RemoteException e) {
14612 }
14613 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014614 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014615 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014616 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014617 }
14618 }
14619
14620 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014621 // Need to do this on its own message because the stack may not
14622 // be in a consistent state at this point.
14623 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014625 }
14626
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014627 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014628 synchronized (this) {
14629 int i;
14630
14631 // First remove any unused application processes whose package
14632 // has been removed.
14633 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14634 final ProcessRecord app = mRemovedProcesses.get(i);
14635 if (app.activities.size() == 0
14636 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014637 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014638 TAG, "Exiting empty application process "
14639 + app.processName + " ("
14640 + (app.thread != null ? app.thread.asBinder() : null)
14641 + ")\n");
14642 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014643 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14644 app.processName, app.setAdj, "empty");
14645 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014646 } else {
14647 try {
14648 app.thread.scheduleExit();
14649 } catch (Exception e) {
14650 // Ignore exceptions.
14651 }
14652 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014653 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014654 mRemovedProcesses.remove(i);
14655
14656 if (app.persistent) {
14657 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014658 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014659 }
14660 }
14661 }
14662 }
14663
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014664 // Now update the oom adj for all processes.
14665 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014666 }
14667 }
14668
14669 /** This method sends the specified signal to each of the persistent apps */
14670 public void signalPersistentProcesses(int sig) throws RemoteException {
14671 if (sig != Process.SIGNAL_USR1) {
14672 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14673 }
14674
14675 synchronized (this) {
14676 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14677 != PackageManager.PERMISSION_GRANTED) {
14678 throw new SecurityException("Requires permission "
14679 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14680 }
14681
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014682 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14683 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014684 if (r.thread != null && r.persistent) {
14685 Process.sendSignal(r.pid, sig);
14686 }
14687 }
14688 }
14689 }
14690
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014691 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14692 if (proc == null || proc == mProfileProc) {
14693 proc = mProfileProc;
14694 path = mProfileFile;
14695 profileType = mProfileType;
14696 clearProfilerLocked();
14697 }
14698 if (proc == null) {
14699 return;
14700 }
14701 try {
14702 proc.thread.profilerControl(false, path, null, profileType);
14703 } catch (RemoteException e) {
14704 throw new IllegalStateException("Process disappeared");
14705 }
14706 }
14707
14708 private void clearProfilerLocked() {
14709 if (mProfileFd != null) {
14710 try {
14711 mProfileFd.close();
14712 } catch (IOException e) {
14713 }
14714 }
14715 mProfileApp = null;
14716 mProfileProc = null;
14717 mProfileFile = null;
14718 mProfileType = 0;
14719 mAutoStopProfiler = false;
14720 }
14721
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014722 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014723 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014724
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014725 try {
14726 synchronized (this) {
14727 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14728 // its own permission.
14729 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14730 != PackageManager.PERMISSION_GRANTED) {
14731 throw new SecurityException("Requires permission "
14732 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014733 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014734
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014735 if (start && fd == null) {
14736 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014737 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014738
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014739 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014740 if (process != null) {
14741 try {
14742 int pid = Integer.parseInt(process);
14743 synchronized (mPidsSelfLocked) {
14744 proc = mPidsSelfLocked.get(pid);
14745 }
14746 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014747 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014748
14749 if (proc == null) {
14750 HashMap<String, SparseArray<ProcessRecord>> all
14751 = mProcessNames.getMap();
14752 SparseArray<ProcessRecord> procs = all.get(process);
14753 if (procs != null && procs.size() > 0) {
14754 proc = procs.valueAt(0);
14755 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014756 }
14757 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014758
14759 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014760 throw new IllegalArgumentException("Unknown process: " + process);
14761 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014762
14763 if (start) {
14764 stopProfilerLocked(null, null, 0);
14765 setProfileApp(proc.info, proc.processName, path, fd, false);
14766 mProfileProc = proc;
14767 mProfileType = profileType;
14768 try {
14769 fd = fd.dup();
14770 } catch (IOException e) {
14771 fd = null;
14772 }
14773 proc.thread.profilerControl(start, path, fd, profileType);
14774 fd = null;
14775 mProfileFd = null;
14776 } else {
14777 stopProfilerLocked(proc, path, profileType);
14778 if (fd != null) {
14779 try {
14780 fd.close();
14781 } catch (IOException e) {
14782 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014783 }
14784 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014785
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014786 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014787 }
14788 } catch (RemoteException e) {
14789 throw new IllegalStateException("Process disappeared");
14790 } finally {
14791 if (fd != null) {
14792 try {
14793 fd.close();
14794 } catch (IOException e) {
14795 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014796 }
14797 }
14798 }
Andy McFadden824c5102010-07-09 16:26:57 -070014799
14800 public boolean dumpHeap(String process, boolean managed,
14801 String path, ParcelFileDescriptor fd) throws RemoteException {
14802
14803 try {
14804 synchronized (this) {
14805 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14806 // its own permission (same as profileControl).
14807 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14808 != PackageManager.PERMISSION_GRANTED) {
14809 throw new SecurityException("Requires permission "
14810 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14811 }
14812
14813 if (fd == null) {
14814 throw new IllegalArgumentException("null fd");
14815 }
14816
14817 ProcessRecord proc = null;
14818 try {
14819 int pid = Integer.parseInt(process);
14820 synchronized (mPidsSelfLocked) {
14821 proc = mPidsSelfLocked.get(pid);
14822 }
14823 } catch (NumberFormatException e) {
14824 }
14825
14826 if (proc == null) {
14827 HashMap<String, SparseArray<ProcessRecord>> all
14828 = mProcessNames.getMap();
14829 SparseArray<ProcessRecord> procs = all.get(process);
14830 if (procs != null && procs.size() > 0) {
14831 proc = procs.valueAt(0);
14832 }
14833 }
14834
14835 if (proc == null || proc.thread == null) {
14836 throw new IllegalArgumentException("Unknown process: " + process);
14837 }
14838
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014839 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14840 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014841 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14842 throw new SecurityException("Process not debuggable: " + proc);
14843 }
14844 }
14845
14846 proc.thread.dumpHeap(managed, path, fd);
14847 fd = null;
14848 return true;
14849 }
14850 } catch (RemoteException e) {
14851 throw new IllegalStateException("Process disappeared");
14852 } finally {
14853 if (fd != null) {
14854 try {
14855 fd.close();
14856 } catch (IOException e) {
14857 }
14858 }
14859 }
14860 }
14861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014862 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14863 public void monitor() {
14864 synchronized (this) { }
14865 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014866
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014867 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014868 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14869 ProcessRecord processRecord = mLruProcesses.get(i);
14870 try {
14871 if (processRecord.thread != null) {
14872 processRecord.thread.setCoreSettings(settings);
14873 }
14874 } catch (RemoteException re) {
14875 /* ignore */
14876 }
14877 }
14878 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014879
14880 // Multi-user methods
14881
Amith Yamasani742a6712011-05-04 14:49:28 -070014882 private int mCurrentUserId;
14883 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14884
14885 public boolean switchUser(int userId) {
14886 final int callingUid = Binder.getCallingUid();
14887 if (callingUid != 0 && callingUid != Process.myUid()) {
14888 Slog.e(TAG, "Trying to switch user from unauthorized app");
14889 return false;
14890 }
14891 if (mCurrentUserId == userId)
14892 return true;
14893
14894 synchronized (this) {
14895 // Check if user is already logged in, otherwise check if user exists first before
14896 // adding to the list of logged in users.
14897 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14898 if (!userExists(userId)) {
14899 return false;
14900 }
14901 mLoggedInUsers.append(userId, userId);
14902 }
14903
14904 mCurrentUserId = userId;
14905 boolean haveActivities = mMainStack.switchUser(userId);
14906 if (!haveActivities) {
14907 startHomeActivityLocked(userId);
14908 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014909
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014910 }
Amith Yamasani13593602012-03-22 16:16:17 -070014911
14912 // Inform of user switch
14913 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14914 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14915 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14916
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014917 return true;
14918 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014919
Amith Yamasani52f1d752012-03-28 18:19:29 -070014920 @Override
14921 public UserInfo getCurrentUser() throws RemoteException {
14922 final int callingUid = Binder.getCallingUid();
14923 if (callingUid != 0 && callingUid != Process.myUid()) {
14924 Slog.e(TAG, "Trying to get user from unauthorized app");
14925 return null;
14926 }
14927 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14928 }
14929
Amith Yamasani13593602012-03-22 16:16:17 -070014930 private void onUserRemoved(Intent intent) {
14931 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14932 if (extraUserId < 1) return;
14933
14934 // Kill all the processes for the user
14935 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14936 synchronized (this) {
14937 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14938 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14939 SparseArray<ProcessRecord> uids = uidMap.getValue();
14940 for (int i = 0; i < uids.size(); i++) {
14941 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14942 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14943 }
14944 }
14945 }
14946
14947 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14948 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14949 false, false, true, true, extraUserId);
14950 }
14951 }
14952 }
14953
Amith Yamasani742a6712011-05-04 14:49:28 -070014954 private boolean userExists(int userId) {
14955 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014956 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14957 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014958 } catch (RemoteException re) {
14959 // Won't happen, in same process
14960 }
14961
14962 return false;
14963 }
14964
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014965 private void checkValidCaller(int uid, int userId) {
14966 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14967
14968 throw new SecurityException("Caller uid=" + uid
14969 + " is not privileged to communicate with user=" + userId);
14970 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014971
14972 private int applyUserId(int uid, int userId) {
14973 return UserId.getUid(userId, uid);
14974 }
14975
14976 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014977 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014978 ApplicationInfo newInfo = new ApplicationInfo(info);
14979 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014980 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14981 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014982 return newInfo;
14983 }
14984
14985 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014986 if (aInfo == null
14987 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014988 return aInfo;
14989 }
14990
14991 ActivityInfo info = new ActivityInfo(aInfo);
14992 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14993 return info;
14994 }
14995
14996 static class ServiceMap {
14997
14998 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14999 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15000 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15001 mServicesByIntentPerUser = new SparseArray<
15002 HashMap<Intent.FilterComparison, ServiceRecord>>();
15003
15004 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15005 // TODO: Deal with global services
15006 if (DEBUG_MU)
15007 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15008 return getServices(callingUser).get(name);
15009 }
15010
15011 ServiceRecord getServiceByName(ComponentName name) {
15012 return getServiceByName(name, -1);
15013 }
15014
15015 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15016 // TODO: Deal with global services
15017 if (DEBUG_MU)
15018 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15019 return getServicesByIntent(callingUser).get(filter);
15020 }
15021
15022 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15023 return getServiceByIntent(filter, -1);
15024 }
15025
15026 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15027 // TODO: Deal with global services
15028 getServices(callingUser).put(name, value);
15029 }
15030
15031 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15032 ServiceRecord value) {
15033 // TODO: Deal with global services
15034 getServicesByIntent(callingUser).put(filter, value);
15035 }
15036
15037 void removeServiceByName(ComponentName name, int callingUser) {
15038 // TODO: Deal with global services
15039 ServiceRecord removed = getServices(callingUser).remove(name);
15040 if (DEBUG_MU)
15041 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15042 + " removed=" + removed);
15043 }
15044
15045 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15046 // TODO: Deal with global services
15047 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15048 if (DEBUG_MU)
15049 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15050 + " removed=" + removed);
15051 }
15052
15053 Collection<ServiceRecord> getAllServices(int callingUser) {
15054 // TODO: Deal with global services
15055 return getServices(callingUser).values();
15056 }
15057
15058 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15059 HashMap map = mServicesByNamePerUser.get(callingUser);
15060 if (map == null) {
15061 map = new HashMap<ComponentName, ServiceRecord>();
15062 mServicesByNamePerUser.put(callingUser, map);
15063 }
15064 return map;
15065 }
15066
15067 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15068 int callingUser) {
15069 HashMap map = mServicesByIntentPerUser.get(callingUser);
15070 if (map == null) {
15071 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15072 mServicesByIntentPerUser.put(callingUser, map);
15073 }
15074 return map;
15075 }
15076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015077}