blob: aa7de826b09ddd93d866cbb322c736b17b9375a8 [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 Hackborn7d608422011-08-07 16:24:18 -07005363 outInfo.threshold = homeAppMem;
5364 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5365 outInfo.hiddenAppThreshold = hiddenAppMem;
5366 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005367 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005368 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5369 ProcessList.VISIBLE_APP_ADJ);
5370 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5371 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 }
5373
5374 // =========================================================
5375 // TASK MANAGEMENT
5376 // =========================================================
5377
5378 public List getTasks(int maxNum, int flags,
5379 IThumbnailReceiver receiver) {
5380 ArrayList list = new ArrayList();
5381
5382 PendingThumbnailsRecord pending = null;
5383 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005384 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385
5386 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005387 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5389 + ", receiver=" + receiver);
5390
5391 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5392 != PackageManager.PERMISSION_GRANTED) {
5393 if (receiver != null) {
5394 // If the caller wants to wait for pending thumbnails,
5395 // it ain't gonna get them.
5396 try {
5397 receiver.finished();
5398 } catch (RemoteException ex) {
5399 }
5400 }
5401 String msg = "Permission Denial: getTasks() from pid="
5402 + Binder.getCallingPid()
5403 + ", uid=" + Binder.getCallingUid()
5404 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005405 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005406 throw new SecurityException(msg);
5407 }
5408
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005409 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005410 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005411 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005412 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 TaskRecord curTask = null;
5414 int numActivities = 0;
5415 int numRunning = 0;
5416 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005417 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005419 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420
5421 // Initialize state for next task if needed.
5422 if (top == null ||
5423 (top.state == ActivityState.INITIALIZING
5424 && top.task == r.task)) {
5425 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 curTask = r.task;
5427 numActivities = numRunning = 0;
5428 }
5429
5430 // Add 'r' into the current task.
5431 numActivities++;
5432 if (r.app != null && r.app.thread != null) {
5433 numRunning++;
5434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435
Joe Onorato8a9b2202010-02-26 18:56:32 -08005436 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 TAG, r.intent.getComponent().flattenToShortString()
5438 + ": task=" + r.task);
5439
5440 // If the next one is a different task, generate a new
5441 // TaskInfo entry for what we have.
5442 if (next == null || next.task != curTask) {
5443 ActivityManager.RunningTaskInfo ci
5444 = new ActivityManager.RunningTaskInfo();
5445 ci.id = curTask.taskId;
5446 ci.baseActivity = r.intent.getComponent();
5447 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005448 if (top.thumbHolder != null) {
5449 ci.description = top.thumbHolder.lastDescription;
5450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 ci.numActivities = numActivities;
5452 ci.numRunning = numRunning;
5453 //System.out.println(
5454 // "#" + maxNum + ": " + " descr=" + ci.description);
5455 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005456 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 TAG, "State=" + top.state + "Idle=" + top.idle
5458 + " app=" + top.app
5459 + " thr=" + (top.app != null ? top.app.thread : null));
5460 if (top.state == ActivityState.RESUMED
5461 || top.state == ActivityState.PAUSING) {
5462 if (top.idle && top.app != null
5463 && top.app.thread != null) {
5464 topRecord = top;
5465 topThumbnail = top.app.thread;
5466 } else {
5467 top.thumbnailNeeded = true;
5468 }
5469 }
5470 if (pending == null) {
5471 pending = new PendingThumbnailsRecord(receiver);
5472 }
5473 pending.pendingRecords.add(top);
5474 }
5475 list.add(ci);
5476 maxNum--;
5477 top = null;
5478 }
5479 }
5480
5481 if (pending != null) {
5482 mPendingThumbnails.add(pending);
5483 }
5484 }
5485
Joe Onorato8a9b2202010-02-26 18:56:32 -08005486 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487
5488 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005489 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005491 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005493 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005494 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 }
5496 }
5497
5498 if (pending == null && receiver != null) {
5499 // In this case all thumbnails were available and the client
5500 // is being asked to be told when the remaining ones come in...
5501 // which is unusually, since the top-most currently running
5502 // activity should never have a canned thumbnail! Oh well.
5503 try {
5504 receiver.finished();
5505 } catch (RemoteException ex) {
5506 }
5507 }
5508
5509 return list;
5510 }
5511
5512 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5513 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005514 final int callingUid = Binder.getCallingUid();
5515 // If it's the system uid asking, then use the current user id.
5516 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5517 // require the entire list.
5518 final int callingUserId = callingUid == Process.SYSTEM_UID
5519 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 synchronized (this) {
5521 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5522 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005523 final boolean detailed = checkCallingPermission(
5524 android.Manifest.permission.GET_DETAILED_TASKS)
5525 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005527 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 final int N = mRecentTasks.size();
5530 ArrayList<ActivityManager.RecentTaskInfo> res
5531 = new ArrayList<ActivityManager.RecentTaskInfo>(
5532 maxNum < N ? maxNum : N);
5533 for (int i=0; i<N && maxNum > 0; i++) {
5534 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005535 // Only add calling user's recent tasks
5536 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005537 // Return the entry if desired by the caller. We always return
5538 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005539 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005540 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5541 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005542
Dianne Hackborn905577f2011-09-07 18:31:28 -07005543 if (i == 0
5544 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 || (tr.intent == null)
5546 || ((tr.intent.getFlags()
5547 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5548 ActivityManager.RecentTaskInfo rti
5549 = new ActivityManager.RecentTaskInfo();
5550 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005551 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 rti.baseIntent = new Intent(
5553 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005554 if (!detailed) {
5555 rti.baseIntent.replaceExtras((Bundle)null);
5556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005558 rti.description = tr.lastDescription;
5559
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005560 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5561 // Check whether this activity is currently available.
5562 try {
5563 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005564 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5565 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005566 continue;
5567 }
5568 } else if (rti.baseIntent != null) {
5569 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005570 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005571 continue;
5572 }
5573 }
5574 } catch (RemoteException e) {
5575 // Will never happen.
5576 }
5577 }
5578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 res.add(rti);
5580 maxNum--;
5581 }
5582 }
5583 return res;
5584 }
5585 }
5586
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005587 private TaskRecord taskForIdLocked(int id) {
5588 final int N = mRecentTasks.size();
5589 for (int i=0; i<N; i++) {
5590 TaskRecord tr = mRecentTasks.get(i);
5591 if (tr.taskId == id) {
5592 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005593 }
5594 }
5595 return null;
5596 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005597
5598 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5599 synchronized (this) {
5600 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5601 "getTaskThumbnails()");
5602 TaskRecord tr = taskForIdLocked(id);
5603 if (tr != null) {
5604 return mMainStack.getTaskThumbnailsLocked(tr);
5605 }
5606 }
5607 return null;
5608 }
5609
5610 public boolean removeSubTask(int taskId, int subTaskIndex) {
5611 synchronized (this) {
5612 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5613 "removeSubTask()");
5614 long ident = Binder.clearCallingIdentity();
5615 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005616 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5617 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005618 } finally {
5619 Binder.restoreCallingIdentity(ident);
5620 }
5621 }
5622 }
5623
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005624 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5625 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005626 Intent baseIntent = new Intent(
5627 tr.intent != null ? tr.intent : tr.affinityIntent);
5628 ComponentName component = baseIntent.getComponent();
5629 if (component == null) {
5630 Slog.w(TAG, "Now component for base intent of task: " + tr);
5631 return;
5632 }
5633
5634 // Find any running services associated with this app.
5635 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005636 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005637 if (sr.packageName.equals(component.getPackageName())) {
5638 services.add(sr);
5639 }
5640 }
5641
5642 // Take care of any running services associated with the app.
5643 for (int i=0; i<services.size(); i++) {
5644 ServiceRecord sr = services.get(i);
5645 if (sr.startRequested) {
5646 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005647 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005648 stopServiceLocked(sr);
5649 } else {
5650 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005651 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005652 if (sr.app != null && sr.app.thread != null) {
5653 sendServiceArgsLocked(sr, false);
5654 }
5655 }
5656 }
5657 }
5658
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005659 if (killProcesses) {
5660 // Find any running processes associated with this app.
5661 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5662 SparseArray<ProcessRecord> appProcs
5663 = mProcessNames.getMap().get(component.getPackageName());
5664 if (appProcs != null) {
5665 for (int i=0; i<appProcs.size(); i++) {
5666 procs.add(appProcs.valueAt(i));
5667 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005668 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005669
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005670 // Kill the running processes.
5671 for (int i=0; i<procs.size(); i++) {
5672 ProcessRecord pr = procs.get(i);
5673 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5674 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5675 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5676 pr.processName, pr.setAdj, "remove task");
5677 Process.killProcessQuiet(pr.pid);
5678 } else {
5679 pr.waitingToKill = "remove task";
5680 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005681 }
5682 }
5683 }
5684
5685 public boolean removeTask(int taskId, int flags) {
5686 synchronized (this) {
5687 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5688 "removeTask()");
5689 long ident = Binder.clearCallingIdentity();
5690 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005691 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5692 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005693 if (r != null) {
5694 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005695 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005696 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005697 } else {
5698 TaskRecord tr = null;
5699 int i=0;
5700 while (i < mRecentTasks.size()) {
5701 TaskRecord t = mRecentTasks.get(i);
5702 if (t.taskId == taskId) {
5703 tr = t;
5704 break;
5705 }
5706 i++;
5707 }
5708 if (tr != null) {
5709 if (tr.numActivities <= 0) {
5710 // Caller is just removing a recent task that is
5711 // not actively running. That is easy!
5712 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005713 cleanUpRemovedTaskLocked(tr, flags);
5714 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005715 } else {
5716 Slog.w(TAG, "removeTask: task " + taskId
5717 + " does not have activities to remove, "
5718 + " but numActivities=" + tr.numActivities
5719 + ": " + tr);
5720 }
5721 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005722 }
5723 } finally {
5724 Binder.restoreCallingIdentity(ident);
5725 }
5726 }
5727 return false;
5728 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5731 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005732 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 TaskRecord jt = startTask;
5734
5735 // First look backwards
5736 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005737 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 if (r.task != jt) {
5739 jt = r.task;
5740 if (affinity.equals(jt.affinity)) {
5741 return j;
5742 }
5743 }
5744 }
5745
5746 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005747 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 jt = startTask;
5749 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005750 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 if (r.task != jt) {
5752 if (affinity.equals(jt.affinity)) {
5753 return j;
5754 }
5755 jt = r.task;
5756 }
5757 }
5758
5759 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005760 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 return N-1;
5762 }
5763
5764 return -1;
5765 }
5766
5767 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005768 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005770 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5772 "moveTaskToFront()");
5773
5774 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005775 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5776 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005777 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005778 return;
5779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 final long origId = Binder.clearCallingIdentity();
5781 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005782 TaskRecord tr = taskForIdLocked(task);
5783 if (tr != null) {
5784 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5785 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005787 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5788 // Caller wants the home activity moved with it. To accomplish this,
5789 // we'll just move the home task to the top first.
5790 mMainStack.moveHomeToFrontLocked();
5791 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005792 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005793 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005795 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5796 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005798 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5799 mMainStack.mUserLeaving = true;
5800 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005801 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5802 // Caller wants the home activity moved with it. To accomplish this,
5803 // we'll just move the home task to the top first.
5804 mMainStack.moveHomeToFrontLocked();
5805 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005806 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 return;
5808 }
5809 }
5810 } finally {
5811 Binder.restoreCallingIdentity(origId);
5812 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005813 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 }
5815 }
5816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 public void moveTaskToBack(int task) {
5818 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5819 "moveTaskToBack()");
5820
5821 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005822 if (mMainStack.mResumedActivity != null
5823 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005824 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5825 Binder.getCallingUid(), "Task to back")) {
5826 return;
5827 }
5828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005830 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 Binder.restoreCallingIdentity(origId);
5832 }
5833 }
5834
5835 /**
5836 * Moves an activity, and all of the other activities within the same task, to the bottom
5837 * of the history stack. The activity's order within the task is unchanged.
5838 *
5839 * @param token A reference to the activity we wish to move
5840 * @param nonRoot If false then this only works if the activity is the root
5841 * of a task; if true it will work for any activity in a task.
5842 * @return Returns true if the move completed, false if not.
5843 */
5844 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005845 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 synchronized(this) {
5847 final long origId = Binder.clearCallingIdentity();
5848 int taskId = getTaskForActivityLocked(token, !nonRoot);
5849 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005850 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 }
5852 Binder.restoreCallingIdentity(origId);
5853 }
5854 return false;
5855 }
5856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 public void moveTaskBackwards(int task) {
5858 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5859 "moveTaskBackwards()");
5860
5861 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005862 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5863 Binder.getCallingUid(), "Task backwards")) {
5864 return;
5865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 final long origId = Binder.clearCallingIdentity();
5867 moveTaskBackwardsLocked(task);
5868 Binder.restoreCallingIdentity(origId);
5869 }
5870 }
5871
5872 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005873 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 }
5875
5876 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5877 synchronized(this) {
5878 return getTaskForActivityLocked(token, onlyRoot);
5879 }
5880 }
5881
5882 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005883 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 TaskRecord lastTask = null;
5885 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005886 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005887 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 if (!onlyRoot || lastTask != r.task) {
5889 return r.task.taskId;
5890 }
5891 return -1;
5892 }
5893 lastTask = r.task;
5894 }
5895
5896 return -1;
5897 }
5898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 // =========================================================
5900 // THUMBNAILS
5901 // =========================================================
5902
5903 public void reportThumbnail(IBinder token,
5904 Bitmap thumbnail, CharSequence description) {
5905 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5906 final long origId = Binder.clearCallingIdentity();
5907 sendPendingThumbnail(null, token, thumbnail, description, true);
5908 Binder.restoreCallingIdentity(origId);
5909 }
5910
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005911 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 Bitmap thumbnail, CharSequence description, boolean always) {
5913 TaskRecord task = null;
5914 ArrayList receivers = null;
5915
5916 //System.out.println("Send pending thumbnail: " + r);
5917
5918 synchronized(this) {
5919 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005920 r = mMainStack.isInStackLocked(token);
5921 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 return;
5923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005924 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005925 if (thumbnail == null && r.thumbHolder != null) {
5926 thumbnail = r.thumbHolder.lastThumbnail;
5927 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 }
5929 if (thumbnail == null && !always) {
5930 // If there is no thumbnail, and this entry is not actually
5931 // going away, then abort for now and pick up the next
5932 // thumbnail we get.
5933 return;
5934 }
5935 task = r.task;
5936
5937 int N = mPendingThumbnails.size();
5938 int i=0;
5939 while (i<N) {
5940 PendingThumbnailsRecord pr =
5941 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5942 //System.out.println("Looking in " + pr.pendingRecords);
5943 if (pr.pendingRecords.remove(r)) {
5944 if (receivers == null) {
5945 receivers = new ArrayList();
5946 }
5947 receivers.add(pr);
5948 if (pr.pendingRecords.size() == 0) {
5949 pr.finished = true;
5950 mPendingThumbnails.remove(i);
5951 N--;
5952 continue;
5953 }
5954 }
5955 i++;
5956 }
5957 }
5958
5959 if (receivers != null) {
5960 final int N = receivers.size();
5961 for (int i=0; i<N; i++) {
5962 try {
5963 PendingThumbnailsRecord pr =
5964 (PendingThumbnailsRecord)receivers.get(i);
5965 pr.receiver.newThumbnail(
5966 task != null ? task.taskId : -1, thumbnail, description);
5967 if (pr.finished) {
5968 pr.receiver.finished();
5969 }
5970 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005971 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 }
5973 }
5974 }
5975 }
5976
5977 // =========================================================
5978 // CONTENT PROVIDERS
5979 // =========================================================
5980
Jeff Brown10e89712011-07-08 18:52:57 -07005981 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5982 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005984 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005985 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005986 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 } catch (RemoteException ex) {
5988 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005989 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005990 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5991 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 if (providers != null) {
5993 final int N = providers.size();
5994 for (int i=0; i<N; i++) {
5995 ProviderInfo cpi =
5996 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005997
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005998 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005999 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006001 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006002 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006004 if (DEBUG_MU)
6005 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 app.pubProviders.put(cpi.name, cpr);
6007 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006008 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 }
6010 }
6011 return providers;
6012 }
6013
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006014 /**
6015 * Check if {@link ProcessRecord} has a possible chance at accessing the
6016 * given {@link ProviderInfo}. Final permission checking is always done
6017 * in {@link ContentProvider}.
6018 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006020 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006022 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006024 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006025 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 return null;
6027 }
6028 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006029 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 == PackageManager.PERMISSION_GRANTED) {
6031 return null;
6032 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006033
6034 PathPermission[] pps = cpi.pathPermissions;
6035 if (pps != null) {
6036 int i = pps.length;
6037 while (i > 0) {
6038 i--;
6039 PathPermission pp = pps[i];
6040 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006041 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006042 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006043 return null;
6044 }
6045 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006046 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006047 == PackageManager.PERMISSION_GRANTED) {
6048 return null;
6049 }
6050 }
6051 }
6052
Dianne Hackbornb424b632010-08-18 15:59:05 -07006053 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6054 if (perms != null) {
6055 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6056 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6057 return null;
6058 }
6059 }
6060 }
6061
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006062 String msg;
6063 if (!cpi.exported) {
6064 msg = "Permission Denial: opening provider " + cpi.name
6065 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6066 + ", uid=" + callingUid + ") that is not exported from uid "
6067 + cpi.applicationInfo.uid;
6068 } else {
6069 msg = "Permission Denial: opening provider " + cpi.name
6070 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6071 + ", uid=" + callingUid + ") requires "
6072 + cpi.readPermission + " or " + cpi.writePermission;
6073 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006074 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 return msg;
6076 }
6077
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006078 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6079 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006080 if (r != null) {
6081 Integer cnt = r.conProviders.get(cpr);
6082 if (DEBUG_PROVIDER) Slog.v(TAG,
6083 "Adding provider requested by "
6084 + r.processName + " from process "
6085 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6086 + " cnt=" + (cnt == null ? 1 : cnt));
6087 if (cnt == null) {
6088 cpr.clients.add(r);
6089 r.conProviders.put(cpr, new Integer(1));
6090 return true;
6091 } else {
6092 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6093 }
6094 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006095 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006096 }
6097 return false;
6098 }
6099
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006100 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6101 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006102 if (r != null) {
6103 Integer cnt = r.conProviders.get(cpr);
6104 if (DEBUG_PROVIDER) Slog.v(TAG,
6105 "Removing provider requested by "
6106 + r.processName + " from process "
6107 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6108 + " cnt=" + cnt);
6109 if (cnt == null || cnt.intValue() <= 1) {
6110 cpr.clients.remove(r);
6111 r.conProviders.remove(cpr);
6112 return true;
6113 } else {
6114 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6115 }
6116 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006117 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006118 }
6119 return false;
6120 }
6121
Amith Yamasani742a6712011-05-04 14:49:28 -07006122 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006123 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 ContentProviderRecord cpr;
6125 ProviderInfo cpi = null;
6126
6127 synchronized(this) {
6128 ProcessRecord r = null;
6129 if (caller != null) {
6130 r = getRecordForAppLocked(caller);
6131 if (r == null) {
6132 throw new SecurityException(
6133 "Unable to find app for caller " + caller
6134 + " (pid=" + Binder.getCallingPid()
6135 + ") when getting content provider " + name);
6136 }
6137 }
6138
6139 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006140 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006141 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006142 boolean providerRunning = cpr != null;
6143 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006145 String msg;
6146 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6147 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 }
6149
6150 if (r != null && cpr.canRunHere(r)) {
6151 // This provider has been published or is in the process
6152 // of being published... but it is also allowed to run
6153 // in the caller's process, so don't make a connection
6154 // and just let the caller instantiate its own instance.
6155 if (cpr.provider != null) {
6156 // don't give caller the provider object, it needs
6157 // to make its own.
6158 cpr = new ContentProviderRecord(cpr);
6159 }
6160 return cpr;
6161 }
6162
6163 final long origId = Binder.clearCallingIdentity();
6164
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006165 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006167 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006168 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006169 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006170 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006171 // make sure to count it as being accessed and thus
6172 // back up on the LRU list. This is good because
6173 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006174 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006175 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006176 }
6177
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006178 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006179 if (false) {
6180 if (cpr.name.flattenToShortString().equals(
6181 "com.android.providers.calendar/.CalendarProvider2")) {
6182 Slog.v(TAG, "****************** KILLING "
6183 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006184 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006185 }
6186 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006187 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006188 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6189 // NOTE: there is still a race here where a signal could be
6190 // pending on the process even though we managed to update its
6191 // adj level. Not sure what to do about this, but at least
6192 // the race is now smaller.
6193 if (!success) {
6194 // Uh oh... it looks like the provider's process
6195 // has been killed on us. We need to wait for a new
6196 // process to be started, and make sure its death
6197 // doesn't kill our process.
6198 Slog.i(TAG,
6199 "Existing provider " + cpr.name.flattenToShortString()
6200 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006201 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006202 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006203 if (!lastRef) {
6204 // This wasn't the last ref our process had on
6205 // the provider... we have now been killed, bail.
6206 return null;
6207 }
6208 providerRunning = false;
6209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 }
6211
6212 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006215 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006217 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006218 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006219 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 } catch (RemoteException ex) {
6221 }
6222 if (cpi == null) {
6223 return null;
6224 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006225 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6226 userId = 0;
6227 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006228 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006229
Dianne Hackbornb424b632010-08-18 15:59:05 -07006230 String msg;
6231 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6232 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 }
6234
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006235 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006236 && !cpi.processName.equals("system")) {
6237 // If this content provider does not run in the system
6238 // process, and the system is not yet ready to run other
6239 // processes, then fail fast instead of hanging.
6240 throw new IllegalArgumentException(
6241 "Attempt to launch content provider before system ready");
6242 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006243
6244 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006245 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 final boolean firstClass = cpr == null;
6247 if (firstClass) {
6248 try {
6249 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006250 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 getApplicationInfo(
6252 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006253 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006255 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 + cpi.name);
6257 return null;
6258 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006259 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006260 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 } catch (RemoteException ex) {
6262 // pm is in same process, this will never happen.
6263 }
6264 }
6265
6266 if (r != null && cpr.canRunHere(r)) {
6267 // If this is a multiprocess provider, then just return its
6268 // info and allow the caller to instantiate it. Only do
6269 // this if the provider is the same user as the caller's
6270 // process, or can run as root (so can be in any process).
6271 return cpr;
6272 }
6273
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006274 if (DEBUG_PROVIDER) {
6275 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006276 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006277 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 }
6279
6280 // This is single process, and our app is now connecting to it.
6281 // See if we are already in the process of launching this
6282 // provider.
6283 final int N = mLaunchingProviders.size();
6284 int i;
6285 for (i=0; i<N; i++) {
6286 if (mLaunchingProviders.get(i) == cpr) {
6287 break;
6288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 }
6290
6291 // If the provider is not already being launched, then get it
6292 // started.
6293 if (i >= N) {
6294 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006295
6296 try {
6297 // Content provider is now in use, its package can't be stopped.
6298 try {
6299 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006300 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006301 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006302 } catch (IllegalArgumentException e) {
6303 Slog.w(TAG, "Failed trying to unstop package "
6304 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006305 }
6306
6307 ProcessRecord proc = startProcessLocked(cpi.processName,
6308 cpr.appInfo, false, 0, "content provider",
6309 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006310 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006311 if (proc == null) {
6312 Slog.w(TAG, "Unable to launch app "
6313 + cpi.applicationInfo.packageName + "/"
6314 + cpi.applicationInfo.uid + " for provider "
6315 + name + ": process is bad");
6316 return null;
6317 }
6318 cpr.launchingApp = proc;
6319 mLaunchingProviders.add(cpr);
6320 } finally {
6321 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 }
6324
6325 // Make sure the provider is published (the same provider class
6326 // may be published under multiple names).
6327 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006328 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006330
Amith Yamasani742a6712011-05-04 14:49:28 -07006331 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006332 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 }
6334 }
6335
6336 // Wait for the provider to be published...
6337 synchronized (cpr) {
6338 while (cpr.provider == null) {
6339 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006340 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 + cpi.applicationInfo.packageName + "/"
6342 + cpi.applicationInfo.uid + " for provider "
6343 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006344 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 cpi.applicationInfo.packageName,
6346 cpi.applicationInfo.uid, name);
6347 return null;
6348 }
6349 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006350 if (DEBUG_MU) {
6351 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6352 + cpr.launchingApp);
6353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 cpr.wait();
6355 } catch (InterruptedException ex) {
6356 }
6357 }
6358 }
6359 return cpr;
6360 }
6361
6362 public final ContentProviderHolder getContentProvider(
6363 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006364 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 if (caller == null) {
6366 String msg = "null IApplicationThread when getting content provider "
6367 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006368 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 throw new SecurityException(msg);
6370 }
6371
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006372 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 }
6374
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006375 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6376 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6377 "Do not have permission in call getContentProviderExternal()");
6378 return getContentProviderExternalUnchecked(name, token);
6379 }
6380
6381 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6382 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 }
6384
6385 /**
6386 * Drop a content provider from a ProcessRecord's bookkeeping
6387 * @param cpr
6388 */
6389 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006390 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006392 int userId = UserId.getUserId(Binder.getCallingUid());
6393 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006395 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006396 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006397 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 return;
6399 }
6400 final ProcessRecord r = getRecordForAppLocked(caller);
6401 if (r == null) {
6402 throw new SecurityException(
6403 "Unable to find app for caller " + caller +
6404 " when removing content provider " + name);
6405 }
6406 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006407 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006408 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6409 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6410 + r.info.processName + " from process "
6411 + localCpr.appInfo.processName);
6412 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006414 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006415 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 return;
6417 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006418 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006419 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423 }
6424
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006425 public void removeContentProviderExternal(String name, IBinder token) {
6426 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6427 "Do not have permission in call removeContentProviderExternal()");
6428 removeContentProviderExternalUnchecked(name, token);
6429 }
6430
6431 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006433 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6434 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 if(cpr == null) {
6436 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006437 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 return;
6439 }
6440
6441 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006442 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006443 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6444 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006445 if (localCpr.hasExternalProcessHandles()) {
6446 if (localCpr.removeExternalProcessHandleLocked(token)) {
6447 updateOomAdjLocked();
6448 } else {
6449 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6450 + " with no external reference for token: "
6451 + token + ".");
6452 }
6453 } else {
6454 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6455 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 }
6458 }
6459
6460 public final void publishContentProviders(IApplicationThread caller,
6461 List<ContentProviderHolder> providers) {
6462 if (providers == null) {
6463 return;
6464 }
6465
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006466 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 synchronized(this) {
6468 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006469 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006470 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 if (r == null) {
6472 throw new SecurityException(
6473 "Unable to find app for caller " + caller
6474 + " (pid=" + Binder.getCallingPid()
6475 + ") when publishing content providers");
6476 }
6477
6478 final long origId = Binder.clearCallingIdentity();
6479
6480 final int N = providers.size();
6481 for (int i=0; i<N; i++) {
6482 ContentProviderHolder src = providers.get(i);
6483 if (src == null || src.info == null || src.provider == null) {
6484 continue;
6485 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006486 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006487 if (DEBUG_MU)
6488 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006490 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006491 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 String names[] = dst.info.authority.split(";");
6493 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006494 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496
6497 int NL = mLaunchingProviders.size();
6498 int j;
6499 for (j=0; j<NL; j++) {
6500 if (mLaunchingProviders.get(j) == dst) {
6501 mLaunchingProviders.remove(j);
6502 j--;
6503 NL--;
6504 }
6505 }
6506 synchronized (dst) {
6507 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006508 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 dst.notifyAll();
6510 }
6511 updateOomAdjLocked(r);
6512 }
6513 }
6514
6515 Binder.restoreCallingIdentity(origId);
6516 }
6517 }
6518
6519 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006520 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006521 synchronized (mSelf) {
6522 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6523 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006524 if (providers != null) {
6525 for (int i=providers.size()-1; i>=0; i--) {
6526 ProviderInfo pi = (ProviderInfo)providers.get(i);
6527 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6528 Slog.w(TAG, "Not installing system proc provider " + pi.name
6529 + ": not system .apk");
6530 providers.remove(i);
6531 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006532 }
6533 }
6534 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006535 if (providers != null) {
6536 mSystemThread.installSystemProviders(providers);
6537 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006538
6539 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006540
6541 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 }
6543
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006544 /**
6545 * Allows app to retrieve the MIME type of a URI without having permission
6546 * to access its content provider.
6547 *
6548 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6549 *
6550 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6551 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6552 */
6553 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006554 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006555 final String name = uri.getAuthority();
6556 final long ident = Binder.clearCallingIdentity();
6557 ContentProviderHolder holder = null;
6558
6559 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006560 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006561 if (holder != null) {
6562 return holder.provider.getType(uri);
6563 }
6564 } catch (RemoteException e) {
6565 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6566 return null;
6567 } finally {
6568 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006569 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006570 }
6571 Binder.restoreCallingIdentity(ident);
6572 }
6573
6574 return null;
6575 }
6576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 // =========================================================
6578 // GLOBAL MANAGEMENT
6579 // =========================================================
6580
6581 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006582 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 String proc = customProcess != null ? customProcess : info.processName;
6584 BatteryStatsImpl.Uid.Proc ps = null;
6585 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006586 int uid = info.uid;
6587 if (isolated) {
6588 int userId = UserId.getUserId(uid);
6589 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6590 uid = 0;
6591 while (true) {
6592 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6593 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6594 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6595 }
6596 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6597 mNextIsolatedProcessUid++;
6598 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6599 // No process for this uid, use it.
6600 break;
6601 }
6602 stepsLeft--;
6603 if (stepsLeft <= 0) {
6604 return null;
6605 }
6606 }
6607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 synchronized (stats) {
6609 ps = stats.getProcessStatsLocked(info.uid, proc);
6610 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006611 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 }
6613
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006614 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6615 ProcessRecord app;
6616 if (!isolated) {
6617 app = getProcessRecordLocked(info.processName, info.uid);
6618 } else {
6619 app = null;
6620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621
6622 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006623 app = newProcessRecordLocked(null, info, null, isolated);
6624 mProcessNames.put(info.processName, app.uid, app);
6625 if (isolated) {
6626 mIsolatedProcesses.put(app.uid, app);
6627 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006628 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 }
6630
Dianne Hackborne7f97212011-02-24 14:40:20 -08006631 // This package really, really can not be stopped.
6632 try {
6633 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006634 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006635 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006636 } catch (IllegalArgumentException e) {
6637 Slog.w(TAG, "Failed trying to unstop package "
6638 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006639 }
6640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6642 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6643 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006644 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 }
6646 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6647 mPersistentStartingProcesses.add(app);
6648 startProcessLocked(app, "added application", app.processName);
6649 }
6650
6651 return app;
6652 }
6653
6654 public void unhandledBack() {
6655 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6656 "unhandledBack()");
6657
6658 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006659 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006660 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 TAG, "Performing unhandledBack(): stack size = " + count);
6662 if (count > 1) {
6663 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006664 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6666 Binder.restoreCallingIdentity(origId);
6667 }
6668 }
6669 }
6670
6671 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006672 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006674 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 ParcelFileDescriptor pfd = null;
6676 if (cph != null) {
6677 // We record the binder invoker's uid in thread-local storage before
6678 // going to the content provider to open the file. Later, in the code
6679 // that handles all permissions checks, we look for this uid and use
6680 // that rather than the Activity Manager's own uid. The effect is that
6681 // we do the check against the caller's permissions even though it looks
6682 // to the content provider like the Activity Manager itself is making
6683 // the request.
6684 sCallerIdentity.set(new Identity(
6685 Binder.getCallingPid(), Binder.getCallingUid()));
6686 try {
6687 pfd = cph.provider.openFile(uri, "r");
6688 } catch (FileNotFoundException e) {
6689 // do nothing; pfd will be returned null
6690 } finally {
6691 // Ensure that whatever happens, we clean up the identity state
6692 sCallerIdentity.remove();
6693 }
6694
6695 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006696 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006698 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 }
6700 return pfd;
6701 }
6702
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006703 // Actually is sleeping or shutting down or whatever else in the future
6704 // is an inactive state.
6705 public boolean isSleeping() {
6706 return mSleeping || mShuttingDown;
6707 }
6708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006710 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6711 != PackageManager.PERMISSION_GRANTED) {
6712 throw new SecurityException("Requires permission "
6713 + android.Manifest.permission.DEVICE_POWER);
6714 }
6715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006717 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006718 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006720 if (!mSleeping) {
6721 mSleeping = true;
6722 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006723
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006724 // Initialize the wake times of all processes.
6725 checkExcessivePowerUsageLocked(false);
6726 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6727 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6728 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
6731 }
6732
Dianne Hackborn55280a92009-05-07 15:53:46 -07006733 public boolean shutdown(int timeout) {
6734 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6735 != PackageManager.PERMISSION_GRANTED) {
6736 throw new SecurityException("Requires permission "
6737 + android.Manifest.permission.SHUTDOWN);
6738 }
6739
6740 boolean timedout = false;
6741
6742 synchronized(this) {
6743 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006744 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006745
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006746 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006747 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006748 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006749 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006750 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006751 long delay = endTime - System.currentTimeMillis();
6752 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006753 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006754 timedout = true;
6755 break;
6756 }
6757 try {
6758 this.wait();
6759 } catch (InterruptedException e) {
6760 }
6761 }
6762 }
6763 }
6764
6765 mUsageStatsService.shutdown();
6766 mBatteryStatsService.shutdown();
6767
6768 return timedout;
6769 }
6770
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006771 public final void activitySlept(IBinder token) {
6772 if (localLOGV) Slog.v(
6773 TAG, "Activity slept: token=" + token);
6774
6775 ActivityRecord r = null;
6776
6777 final long origId = Binder.clearCallingIdentity();
6778
6779 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006780 r = mMainStack.isInStackLocked(token);
6781 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006782 mMainStack.activitySleptLocked(r);
6783 }
6784 }
6785
6786 Binder.restoreCallingIdentity(origId);
6787 }
6788
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006789 private void comeOutOfSleepIfNeededLocked() {
6790 if (!mWentToSleep && !mLockScreenShown) {
6791 if (mSleeping) {
6792 mSleeping = false;
6793 mMainStack.awakeFromSleepingLocked();
6794 mMainStack.resumeTopActivityLocked(null);
6795 }
6796 }
6797 }
6798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006800 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6801 != PackageManager.PERMISSION_GRANTED) {
6802 throw new SecurityException("Requires permission "
6803 + android.Manifest.permission.DEVICE_POWER);
6804 }
6805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006807 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006808 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006809 comeOutOfSleepIfNeededLocked();
6810 }
6811 }
6812
Jeff Brownc042ee22012-05-08 13:03:42 -07006813 private void updateEventDispatchingLocked() {
6814 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6815 }
6816
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006817 public void setLockScreenShown(boolean shown) {
6818 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6819 != PackageManager.PERMISSION_GRANTED) {
6820 throw new SecurityException("Requires permission "
6821 + android.Manifest.permission.DEVICE_POWER);
6822 }
6823
6824 synchronized(this) {
6825 mLockScreenShown = shown;
6826 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 }
6828 }
6829
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006830 public void stopAppSwitches() {
6831 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6832 != PackageManager.PERMISSION_GRANTED) {
6833 throw new SecurityException("Requires permission "
6834 + android.Manifest.permission.STOP_APP_SWITCHES);
6835 }
6836
6837 synchronized(this) {
6838 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6839 + APP_SWITCH_DELAY_TIME;
6840 mDidAppSwitch = false;
6841 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6842 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6843 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6844 }
6845 }
6846
6847 public void resumeAppSwitches() {
6848 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6849 != PackageManager.PERMISSION_GRANTED) {
6850 throw new SecurityException("Requires permission "
6851 + android.Manifest.permission.STOP_APP_SWITCHES);
6852 }
6853
6854 synchronized(this) {
6855 // Note that we don't execute any pending app switches... we will
6856 // let those wait until either the timeout, or the next start
6857 // activity request.
6858 mAppSwitchesAllowedTime = 0;
6859 }
6860 }
6861
6862 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6863 String name) {
6864 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6865 return true;
6866 }
6867
6868 final int perm = checkComponentPermission(
6869 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006870 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006871 if (perm == PackageManager.PERMISSION_GRANTED) {
6872 return true;
6873 }
6874
Joe Onorato8a9b2202010-02-26 18:56:32 -08006875 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006876 return false;
6877 }
6878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006879 public void setDebugApp(String packageName, boolean waitForDebugger,
6880 boolean persistent) {
6881 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6882 "setDebugApp()");
6883
6884 // Note that this is not really thread safe if there are multiple
6885 // callers into it at the same time, but that's not a situation we
6886 // care about.
6887 if (persistent) {
6888 final ContentResolver resolver = mContext.getContentResolver();
6889 Settings.System.putString(
6890 resolver, Settings.System.DEBUG_APP,
6891 packageName);
6892 Settings.System.putInt(
6893 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6894 waitForDebugger ? 1 : 0);
6895 }
6896
6897 synchronized (this) {
6898 if (!persistent) {
6899 mOrigDebugApp = mDebugApp;
6900 mOrigWaitForDebugger = mWaitForDebugger;
6901 }
6902 mDebugApp = packageName;
6903 mWaitForDebugger = waitForDebugger;
6904 mDebugTransient = !persistent;
6905 if (packageName != null) {
6906 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006907 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006908 Binder.restoreCallingIdentity(origId);
6909 }
6910 }
6911 }
6912
Siva Velusamy92a8b222012-03-09 16:24:04 -08006913 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6914 synchronized (this) {
6915 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6916 if (!isDebuggable) {
6917 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6918 throw new SecurityException("Process not debuggable: " + app.packageName);
6919 }
6920 }
6921
6922 mOpenGlTraceApp = processName;
6923 }
6924 }
6925
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006926 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6927 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6928 synchronized (this) {
6929 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6930 if (!isDebuggable) {
6931 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6932 throw new SecurityException("Process not debuggable: " + app.packageName);
6933 }
6934 }
6935 mProfileApp = processName;
6936 mProfileFile = profileFile;
6937 if (mProfileFd != null) {
6938 try {
6939 mProfileFd.close();
6940 } catch (IOException e) {
6941 }
6942 mProfileFd = null;
6943 }
6944 mProfileFd = profileFd;
6945 mProfileType = 0;
6946 mAutoStopProfiler = autoStopProfiler;
6947 }
6948 }
6949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 public void setAlwaysFinish(boolean enabled) {
6951 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6952 "setAlwaysFinish()");
6953
6954 Settings.System.putInt(
6955 mContext.getContentResolver(),
6956 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6957
6958 synchronized (this) {
6959 mAlwaysFinishActivities = enabled;
6960 }
6961 }
6962
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006963 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006964 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006965 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006967 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006968 }
6969 }
6970
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006971 public boolean isUserAMonkey() {
6972 // For now the fact that there is a controller implies
6973 // we have a monkey.
6974 synchronized (this) {
6975 return mController != null;
6976 }
6977 }
6978
Jeff Sharkeya4620792011-05-20 15:29:23 -07006979 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006980 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6981 "registerProcessObserver()");
6982 synchronized (this) {
6983 mProcessObservers.register(observer);
6984 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006985 }
6986
6987 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006988 synchronized (this) {
6989 mProcessObservers.unregister(observer);
6990 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006991 }
6992
Daniel Sandler69a48172010-06-23 16:29:36 -04006993 public void setImmersive(IBinder token, boolean immersive) {
6994 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006995 ActivityRecord r = mMainStack.isInStackLocked(token);
6996 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006997 throw new IllegalArgumentException();
6998 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006999 r.immersive = immersive;
7000 }
7001 }
7002
7003 public boolean isImmersive(IBinder token) {
7004 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007005 ActivityRecord r = mMainStack.isInStackLocked(token);
7006 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007007 throw new IllegalArgumentException();
7008 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007009 return r.immersive;
7010 }
7011 }
7012
7013 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007014 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007015 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007016 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007017 return (r != null) ? r.immersive : false;
7018 }
7019 }
7020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 public final void enterSafeMode() {
7022 synchronized(this) {
7023 // It only makes sense to do this before the system is ready
7024 // and started launching other packages.
7025 if (!mSystemReady) {
7026 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007027 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 } catch (RemoteException e) {
7029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 }
7031 }
7032 }
7033
Jeff Brownb09abc12011-01-13 21:08:27 -08007034 public final void showSafeModeOverlay() {
7035 View v = LayoutInflater.from(mContext).inflate(
7036 com.android.internal.R.layout.safe_mode, null);
7037 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7038 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7039 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7040 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7041 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7042 lp.format = v.getBackground().getOpacity();
7043 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7044 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7045 ((WindowManager)mContext.getSystemService(
7046 Context.WINDOW_SERVICE)).addView(v, lp);
7047 }
7048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 public void noteWakeupAlarm(IIntentSender sender) {
7050 if (!(sender instanceof PendingIntentRecord)) {
7051 return;
7052 }
7053 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7054 synchronized (stats) {
7055 if (mBatteryStatsService.isOnBattery()) {
7056 mBatteryStatsService.enforceCallingPermission();
7057 PendingIntentRecord rec = (PendingIntentRecord)sender;
7058 int MY_UID = Binder.getCallingUid();
7059 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7060 BatteryStatsImpl.Uid.Pkg pkg =
7061 stats.getPackageStatsLocked(uid, rec.key.packageName);
7062 pkg.incWakeupsLocked();
7063 }
7064 }
7065 }
7066
Dianne Hackborn64825172011-03-02 21:32:58 -08007067 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007069 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007071 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 // XXX Note: don't acquire main activity lock here, because the window
7073 // manager calls in with its locks held.
7074
7075 boolean killed = false;
7076 synchronized (mPidsSelfLocked) {
7077 int[] types = new int[pids.length];
7078 int worstType = 0;
7079 for (int i=0; i<pids.length; i++) {
7080 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7081 if (proc != null) {
7082 int type = proc.setAdj;
7083 types[i] = type;
7084 if (type > worstType) {
7085 worstType = type;
7086 }
7087 }
7088 }
7089
Dianne Hackborn64825172011-03-02 21:32:58 -08007090 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007091 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007092 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7093 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007094 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007096
7097 // If this is not a secure call, don't let it kill processes that
7098 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007099 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7100 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007101 }
7102
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007103 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 for (int i=0; i<pids.length; i++) {
7105 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7106 if (proc == null) {
7107 continue;
7108 }
7109 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007110 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007111 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007112 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7113 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007114 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007115 proc.killedBackground = true;
7116 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 }
7118 }
7119 }
7120 return killed;
7121 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007122
7123 @Override
7124 public boolean killProcessesBelowForeground(String reason) {
7125 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7126 throw new SecurityException("killProcessesBelowForeground() only available to system");
7127 }
7128
7129 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7130 }
7131
7132 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7133 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7134 throw new SecurityException("killProcessesBelowAdj() only available to system");
7135 }
7136
7137 boolean killed = false;
7138 synchronized (mPidsSelfLocked) {
7139 final int size = mPidsSelfLocked.size();
7140 for (int i = 0; i < size; i++) {
7141 final int pid = mPidsSelfLocked.keyAt(i);
7142 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7143 if (proc == null) continue;
7144
7145 final int adj = proc.setAdj;
7146 if (adj > belowAdj && !proc.killedBackground) {
7147 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7148 EventLog.writeEvent(
7149 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7150 killed = true;
7151 proc.killedBackground = true;
7152 Process.killProcessQuiet(pid);
7153 }
7154 }
7155 }
7156 return killed;
7157 }
7158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 public final void startRunning(String pkg, String cls, String action,
7160 String data) {
7161 synchronized(this) {
7162 if (mStartRunning) {
7163 return;
7164 }
7165 mStartRunning = true;
7166 mTopComponent = pkg != null && cls != null
7167 ? new ComponentName(pkg, cls) : null;
7168 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7169 mTopData = data;
7170 if (!mSystemReady) {
7171 return;
7172 }
7173 }
7174
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007175 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 }
7177
7178 private void retrieveSettings() {
7179 final ContentResolver resolver = mContext.getContentResolver();
7180 String debugApp = Settings.System.getString(
7181 resolver, Settings.System.DEBUG_APP);
7182 boolean waitForDebugger = Settings.System.getInt(
7183 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7184 boolean alwaysFinishActivities = Settings.System.getInt(
7185 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7186
7187 Configuration configuration = new Configuration();
7188 Settings.System.getConfiguration(resolver, configuration);
7189
7190 synchronized (this) {
7191 mDebugApp = mOrigDebugApp = debugApp;
7192 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7193 mAlwaysFinishActivities = alwaysFinishActivities;
7194 // This happens before any activities are started, so we can
7195 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007196 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007197 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198 }
7199 }
7200
7201 public boolean testIsSystemReady() {
7202 // no need to synchronize(this) just to read & return the value
7203 return mSystemReady;
7204 }
7205
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007206 private static File getCalledPreBootReceiversFile() {
7207 File dataDir = Environment.getDataDirectory();
7208 File systemDir = new File(dataDir, "system");
7209 File fname = new File(systemDir, "called_pre_boots.dat");
7210 return fname;
7211 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007212
7213 static final int LAST_DONE_VERSION = 10000;
7214
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007215 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7216 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7217 File file = getCalledPreBootReceiversFile();
7218 FileInputStream fis = null;
7219 try {
7220 fis = new FileInputStream(file);
7221 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007222 int fvers = dis.readInt();
7223 if (fvers == LAST_DONE_VERSION) {
7224 String vers = dis.readUTF();
7225 String codename = dis.readUTF();
7226 String build = dis.readUTF();
7227 if (android.os.Build.VERSION.RELEASE.equals(vers)
7228 && android.os.Build.VERSION.CODENAME.equals(codename)
7229 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7230 int num = dis.readInt();
7231 while (num > 0) {
7232 num--;
7233 String pkg = dis.readUTF();
7234 String cls = dis.readUTF();
7235 lastDoneReceivers.add(new ComponentName(pkg, cls));
7236 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007237 }
7238 }
7239 } catch (FileNotFoundException e) {
7240 } catch (IOException e) {
7241 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7242 } finally {
7243 if (fis != null) {
7244 try {
7245 fis.close();
7246 } catch (IOException e) {
7247 }
7248 }
7249 }
7250 return lastDoneReceivers;
7251 }
7252
7253 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7254 File file = getCalledPreBootReceiversFile();
7255 FileOutputStream fos = null;
7256 DataOutputStream dos = null;
7257 try {
7258 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7259 fos = new FileOutputStream(file);
7260 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007261 dos.writeInt(LAST_DONE_VERSION);
7262 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007263 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007264 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007265 dos.writeInt(list.size());
7266 for (int i=0; i<list.size(); i++) {
7267 dos.writeUTF(list.get(i).getPackageName());
7268 dos.writeUTF(list.get(i).getClassName());
7269 }
7270 } catch (IOException e) {
7271 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7272 file.delete();
7273 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007274 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007275 if (dos != null) {
7276 try {
7277 dos.close();
7278 } catch (IOException e) {
7279 // TODO Auto-generated catch block
7280 e.printStackTrace();
7281 }
7282 }
7283 }
7284 }
7285
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007286 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 synchronized(this) {
7288 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007289 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 return;
7291 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007292
7293 // Check to see if there are any update receivers to run.
7294 if (!mDidUpdate) {
7295 if (mWaitingUpdate) {
7296 return;
7297 }
7298 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7299 List<ResolveInfo> ris = null;
7300 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007301 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007302 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007303 } catch (RemoteException e) {
7304 }
7305 if (ris != null) {
7306 for (int i=ris.size()-1; i>=0; i--) {
7307 if ((ris.get(i).activityInfo.applicationInfo.flags
7308 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7309 ris.remove(i);
7310 }
7311 }
7312 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007313
7314 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7315
7316 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007317 for (int i=0; i<ris.size(); i++) {
7318 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007319 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7320 if (lastDoneReceivers.contains(comp)) {
7321 ris.remove(i);
7322 i--;
7323 }
7324 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007325
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007326 for (int i=0; i<ris.size(); i++) {
7327 ActivityInfo ai = ris.get(i).activityInfo;
7328 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7329 doneReceivers.add(comp);
7330 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007331 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007332 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007333 finisher = new IIntentReceiver.Stub() {
7334 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007335 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007336 boolean sticky) {
7337 // The raw IIntentReceiver interface is called
7338 // with the AM lock held, so redispatch to
7339 // execute our code without the lock.
7340 mHandler.post(new Runnable() {
7341 public void run() {
7342 synchronized (ActivityManagerService.this) {
7343 mDidUpdate = true;
7344 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007345 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007346 showBootMessage(mContext.getText(
7347 R.string.android_upgrading_complete),
7348 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007349 systemReady(goingCallback);
7350 }
7351 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007352 }
7353 };
7354 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007355 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007356 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007357 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007358 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007359 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007360 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007361 mWaitingUpdate = true;
7362 }
7363 }
7364 }
7365 if (mWaitingUpdate) {
7366 return;
7367 }
7368 mDidUpdate = true;
7369 }
7370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 mSystemReady = true;
7372 if (!mStartRunning) {
7373 return;
7374 }
7375 }
7376
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007377 ArrayList<ProcessRecord> procsToKill = null;
7378 synchronized(mPidsSelfLocked) {
7379 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7380 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7381 if (!isAllowedWhileBooting(proc.info)){
7382 if (procsToKill == null) {
7383 procsToKill = new ArrayList<ProcessRecord>();
7384 }
7385 procsToKill.add(proc);
7386 }
7387 }
7388 }
7389
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007390 synchronized(this) {
7391 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007392 for (int i=procsToKill.size()-1; i>=0; i--) {
7393 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007394 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007395 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007396 }
7397 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007398
7399 // Now that we have cleaned up any update processes, we
7400 // are ready to start launching real processes and know that
7401 // we won't trample on them any more.
7402 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007403 }
7404
Joe Onorato8a9b2202010-02-26 18:56:32 -08007405 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007406 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 SystemClock.uptimeMillis());
7408
7409 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007410 // Make sure we have no pre-ready processes sitting around.
7411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007412 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7413 ResolveInfo ri = mContext.getPackageManager()
7414 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007415 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 CharSequence errorMsg = null;
7417 if (ri != null) {
7418 ActivityInfo ai = ri.activityInfo;
7419 ApplicationInfo app = ai.applicationInfo;
7420 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7421 mTopAction = Intent.ACTION_FACTORY_TEST;
7422 mTopData = null;
7423 mTopComponent = new ComponentName(app.packageName,
7424 ai.name);
7425 } else {
7426 errorMsg = mContext.getResources().getText(
7427 com.android.internal.R.string.factorytest_not_system);
7428 }
7429 } else {
7430 errorMsg = mContext.getResources().getText(
7431 com.android.internal.R.string.factorytest_no_action);
7432 }
7433 if (errorMsg != null) {
7434 mTopAction = null;
7435 mTopData = null;
7436 mTopComponent = null;
7437 Message msg = Message.obtain();
7438 msg.what = SHOW_FACTORY_ERROR_MSG;
7439 msg.getData().putCharSequence("msg", errorMsg);
7440 mHandler.sendMessage(msg);
7441 }
7442 }
7443 }
7444
7445 retrieveSettings();
7446
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007447 if (goingCallback != null) goingCallback.run();
7448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 synchronized (this) {
7450 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7451 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007452 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007453 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 if (apps != null) {
7455 int N = apps.size();
7456 int i;
7457 for (i=0; i<N; i++) {
7458 ApplicationInfo info
7459 = (ApplicationInfo)apps.get(i);
7460 if (info != null &&
7461 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007462 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 }
7464 }
7465 }
7466 } catch (RemoteException ex) {
7467 // pm is in same process, this will never happen.
7468 }
7469 }
7470
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007471 // Start up initial activity.
7472 mBooting = true;
7473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007475 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 Message msg = Message.obtain();
7477 msg.what = SHOW_UID_ERROR_MSG;
7478 mHandler.sendMessage(msg);
7479 }
7480 } catch (RemoteException e) {
7481 }
7482
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007483 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007484 }
7485 }
7486
Dan Egnorb7f03672009-12-09 16:22:32 -08007487 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007488 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007490 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007491 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 startAppProblemLocked(app);
7493 app.stopFreezingAllLocked();
7494 return handleAppCrashLocked(app);
7495 }
7496
Dan Egnorb7f03672009-12-09 16:22:32 -08007497 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007498 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007500 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007501 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7502 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 startAppProblemLocked(app);
7504 app.stopFreezingAllLocked();
7505 }
7506
7507 /**
7508 * Generate a process error record, suitable for attachment to a ProcessRecord.
7509 *
7510 * @param app The ProcessRecord in which the error occurred.
7511 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7512 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007513 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 * @param shortMsg Short message describing the crash.
7515 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007516 * @param stackTrace Full crash stack trace, may be null.
7517 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007518 * @return Returns a fully-formed AppErrorStateInfo record.
7519 */
7520 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007521 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 report.condition = condition;
7525 report.processName = app.processName;
7526 report.pid = app.pid;
7527 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007528 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 report.shortMsg = shortMsg;
7530 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007531 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532
7533 return report;
7534 }
7535
Dan Egnor42471dd2010-01-07 17:25:22 -08007536 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 synchronized (this) {
7538 app.crashing = false;
7539 app.crashingReport = null;
7540 app.notResponding = false;
7541 app.notRespondingReport = null;
7542 if (app.anrDialog == fromDialog) {
7543 app.anrDialog = null;
7544 }
7545 if (app.waitDialog == fromDialog) {
7546 app.waitDialog = null;
7547 }
7548 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007549 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007550 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007551 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7552 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007553 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 }
7556 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007557
Dan Egnorb7f03672009-12-09 16:22:32 -08007558 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007559 if (mHeadless) {
7560 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7561 return false;
7562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 long now = SystemClock.uptimeMillis();
7564
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007565 Long crashTime;
7566 if (!app.isolated) {
7567 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7568 } else {
7569 crashTime = null;
7570 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007571 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007573 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007575 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007576 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007577 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7578 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007580 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007582 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
7584 }
7585 if (!app.persistent) {
7586 // We don't want to start this process again until the user
7587 // explicitly does so... but for persistent process, we really
7588 // need to keep it running. If a persistent process is actually
7589 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007590 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007592 if (!app.isolated) {
7593 // XXX We don't have a way to mark isolated processes
7594 // as bad, since they don't have a peristent identity.
7595 mBadProcesses.put(app.info.processName, app.uid, now);
7596 mProcessCrashTimes.remove(app.info.processName, app.uid);
7597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007600 // Don't let services in this process be restarted and potentially
7601 // annoy the user repeatedly. Unless it is persistent, since those
7602 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007603 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007604 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 return false;
7606 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007607 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007608 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007609 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007610 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007611 // If the top running activity is from this crashing
7612 // process, then terminate it to avoid getting in a loop.
7613 Slog.w(TAG, " Force finishing activity "
7614 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007615 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007616 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007617 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007618 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007619 // stopped, to avoid a situation where one will get
7620 // re-start our crashing activity once it gets resumed again.
7621 index--;
7622 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007623 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007624 if (r.state == ActivityState.RESUMED
7625 || r.state == ActivityState.PAUSING
7626 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007627 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007628 Slog.w(TAG, " Force finishing activity "
7629 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007630 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007631 Activity.RESULT_CANCELED, null, "crashed");
7632 }
7633 }
7634 }
7635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 }
7637
7638 // Bump up the crash count of any services currently running in the proc.
7639 if (app.services.size() != 0) {
7640 // Any services running in the application need to be placed
7641 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007642 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007644 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 sr.crashCount++;
7646 }
7647 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007648
7649 // If the crashing process is what we consider to be the "home process" and it has been
7650 // replaced by a third-party app, clear the package preferred activities from packages
7651 // with a home activity running in the process to prevent a repeatedly crashing app
7652 // from blocking the user to manually clear the list.
7653 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7654 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7655 Iterator it = mHomeProcess.activities.iterator();
7656 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007657 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007658 if (r.isHomeActivity) {
7659 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7660 try {
7661 ActivityThread.getPackageManager()
7662 .clearPackagePreferredActivities(r.packageName);
7663 } catch (RemoteException c) {
7664 // pm is in same process, this will never happen.
7665 }
7666 }
7667 }
7668 }
7669
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007670 if (!app.isolated) {
7671 // XXX Can't keep track of crash times for isolated processes,
7672 // because they don't have a perisistent identity.
7673 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7674 }
7675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007676 return true;
7677 }
7678
7679 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007680 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7681 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 skipCurrentReceiverLocked(app);
7683 }
7684
7685 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007686 for (BroadcastQueue queue : mBroadcastQueues) {
7687 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 }
7689 }
7690
Dan Egnor60d87622009-12-16 16:32:58 -08007691 /**
7692 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7693 * The application process will exit immediately after this call returns.
7694 * @param app object of the crashing app, null for the system server
7695 * @param crashInfo describing the exception
7696 */
7697 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007698 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007699 final String processName = app == null ? "system_server"
7700 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007701
7702 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007703 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007704 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007705 crashInfo.exceptionClassName,
7706 crashInfo.exceptionMessage,
7707 crashInfo.throwFileName,
7708 crashInfo.throwLineNumber);
7709
Jeff Sharkeya353d262011-10-28 11:12:06 -07007710 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007711
7712 crashApplication(r, crashInfo);
7713 }
7714
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007715 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007716 IBinder app,
7717 int violationMask,
7718 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007719 ProcessRecord r = findAppProcess(app, "StrictMode");
7720 if (r == null) {
7721 return;
7722 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007723
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007724 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007725 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007726 boolean logIt = true;
7727 synchronized (mAlreadyLoggedViolatedStacks) {
7728 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7729 logIt = false;
7730 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007731 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007732 // the relative pain numbers, without logging all
7733 // the stack traces repeatedly. We'd want to do
7734 // likewise in the client code, which also does
7735 // dup suppression, before the Binder call.
7736 } else {
7737 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7738 mAlreadyLoggedViolatedStacks.clear();
7739 }
7740 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7741 }
7742 }
7743 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007744 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007745 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007746 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007747
7748 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7749 AppErrorResult result = new AppErrorResult();
7750 synchronized (this) {
7751 final long origId = Binder.clearCallingIdentity();
7752
7753 Message msg = Message.obtain();
7754 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7755 HashMap<String, Object> data = new HashMap<String, Object>();
7756 data.put("result", result);
7757 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007758 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007759 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007760 msg.obj = data;
7761 mHandler.sendMessage(msg);
7762
7763 Binder.restoreCallingIdentity(origId);
7764 }
7765 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007766 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007767 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007768 }
7769
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007770 // Depending on the policy in effect, there could be a bunch of
7771 // these in quick succession so we try to batch these together to
7772 // minimize disk writes, number of dropbox entries, and maximize
7773 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007774 private void logStrictModeViolationToDropBox(
7775 ProcessRecord process,
7776 StrictMode.ViolationInfo info) {
7777 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007778 return;
7779 }
7780 final boolean isSystemApp = process == null ||
7781 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7782 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007783 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007784 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7785 final DropBoxManager dbox = (DropBoxManager)
7786 mContext.getSystemService(Context.DROPBOX_SERVICE);
7787
7788 // Exit early if the dropbox isn't configured to accept this report type.
7789 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7790
7791 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007792 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007793 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7794 synchronized (sb) {
7795 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007796 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007797 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7798 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007799 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7800 if (info.violationNumThisLoop != 0) {
7801 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7802 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007803 if (info.numAnimationsRunning != 0) {
7804 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7805 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007806 if (info.broadcastIntentAction != null) {
7807 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7808 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007809 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007810 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007811 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007812 if (info.numInstances != -1) {
7813 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7814 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007815 if (info.tags != null) {
7816 for (String tag : info.tags) {
7817 sb.append("Span-Tag: ").append(tag).append("\n");
7818 }
7819 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007820 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007821 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7822 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007823 }
7824 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007825
7826 // Only buffer up to ~64k. Various logging bits truncate
7827 // things at 128k.
7828 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007829 }
7830
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007831 // Flush immediately if the buffer's grown too large, or this
7832 // is a non-system app. Non-system apps are isolated with a
7833 // different tag & policy and not batched.
7834 //
7835 // Batching is useful during internal testing with
7836 // StrictMode settings turned up high. Without batching,
7837 // thousands of separate files could be created on boot.
7838 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007839 new Thread("Error dump: " + dropboxTag) {
7840 @Override
7841 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007842 String report;
7843 synchronized (sb) {
7844 report = sb.toString();
7845 sb.delete(0, sb.length());
7846 sb.trimToSize();
7847 }
7848 if (report.length() != 0) {
7849 dbox.addText(dropboxTag, report);
7850 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007851 }
7852 }.start();
7853 return;
7854 }
7855
7856 // System app batching:
7857 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007858 // An existing dropbox-writing thread is outstanding, so
7859 // we don't need to start it up. The existing thread will
7860 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007861 return;
7862 }
7863
7864 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7865 // (After this point, we shouldn't access AMS internal data structures.)
7866 new Thread("Error dump: " + dropboxTag) {
7867 @Override
7868 public void run() {
7869 // 5 second sleep to let stacks arrive and be batched together
7870 try {
7871 Thread.sleep(5000); // 5 seconds
7872 } catch (InterruptedException e) {}
7873
7874 String errorReport;
7875 synchronized (mStrictModeBuffer) {
7876 errorReport = mStrictModeBuffer.toString();
7877 if (errorReport.length() == 0) {
7878 return;
7879 }
7880 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7881 mStrictModeBuffer.trimToSize();
7882 }
7883 dbox.addText(dropboxTag, errorReport);
7884 }
7885 }.start();
7886 }
7887
Dan Egnor60d87622009-12-16 16:32:58 -08007888 /**
7889 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7890 * @param app object of the crashing app, null for the system server
7891 * @param tag reported by the caller
7892 * @param crashInfo describing the context of the error
7893 * @return true if the process should exit immediately (WTF is fatal)
7894 */
7895 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007896 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007897 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007898 final String processName = app == null ? "system_server"
7899 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007900
7901 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007902 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007903 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007904 tag, crashInfo.exceptionMessage);
7905
Jeff Sharkeya353d262011-10-28 11:12:06 -07007906 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007907
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007908 if (r != null && r.pid != Process.myPid() &&
7909 Settings.Secure.getInt(mContext.getContentResolver(),
7910 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007911 crashApplication(r, crashInfo);
7912 return true;
7913 } else {
7914 return false;
7915 }
7916 }
7917
7918 /**
7919 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7920 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7921 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007922 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007923 if (app == null) {
7924 return null;
7925 }
7926
7927 synchronized (this) {
7928 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7929 final int NA = apps.size();
7930 for (int ia=0; ia<NA; ia++) {
7931 ProcessRecord p = apps.valueAt(ia);
7932 if (p.thread != null && p.thread.asBinder() == app) {
7933 return p;
7934 }
7935 }
7936 }
7937
Dianne Hackborncb44d962011-03-10 17:02:27 -08007938 Slog.w(TAG, "Can't find mystery application for " + reason
7939 + " from pid=" + Binder.getCallingPid()
7940 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007941 return null;
7942 }
7943 }
7944
7945 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007946 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7947 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007948 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007949 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7950 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007951 // Watchdog thread ends up invoking this function (with
7952 // a null ProcessRecord) to add the stack file to dropbox.
7953 // Do not acquire a lock on this (am) in such cases, as it
7954 // could cause a potential deadlock, if and when watchdog
7955 // is invoked due to unavailability of lock on am and it
7956 // would prevent watchdog from killing system_server.
7957 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007958 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007959 return;
7960 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007961 // Note: ProcessRecord 'process' is guarded by the service
7962 // instance. (notably process.pkgList, which could otherwise change
7963 // concurrently during execution of this method)
7964 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007965 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007966 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007967 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007968 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7969 for (String pkg : process.pkgList) {
7970 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007971 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007972 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007973 if (pi != null) {
7974 sb.append(" v").append(pi.versionCode);
7975 if (pi.versionName != null) {
7976 sb.append(" (").append(pi.versionName).append(")");
7977 }
7978 }
7979 } catch (RemoteException e) {
7980 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007981 }
Dan Egnora455d192010-03-12 08:52:28 -08007982 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007983 }
Dan Egnora455d192010-03-12 08:52:28 -08007984 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007985 }
7986
7987 private static String processClass(ProcessRecord process) {
7988 if (process == null || process.pid == MY_PID) {
7989 return "system_server";
7990 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7991 return "system_app";
7992 } else {
7993 return "data_app";
7994 }
7995 }
7996
7997 /**
7998 * Write a description of an error (crash, WTF, ANR) to the drop box.
7999 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8000 * @param process which caused the error, null means the system server
8001 * @param activity which triggered the error, null if unknown
8002 * @param parent activity related to the error, null if unknown
8003 * @param subject line related to the error, null if absent
8004 * @param report in long form describing the error, null if absent
8005 * @param logFile to include in the report, null if none
8006 * @param crashInfo giving an application stack trace, null if absent
8007 */
8008 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008009 ProcessRecord process, String processName, ActivityRecord activity,
8010 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008011 final String report, final File logFile,
8012 final ApplicationErrorReport.CrashInfo crashInfo) {
8013 // NOTE -- this must never acquire the ActivityManagerService lock,
8014 // otherwise the watchdog may be prevented from resetting the system.
8015
8016 final String dropboxTag = processClass(process) + "_" + eventType;
8017 final DropBoxManager dbox = (DropBoxManager)
8018 mContext.getSystemService(Context.DROPBOX_SERVICE);
8019
8020 // Exit early if the dropbox isn't configured to accept this report type.
8021 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8022
8023 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008024 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008025 if (activity != null) {
8026 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8027 }
8028 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8029 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8030 }
8031 if (parent != null && parent != activity) {
8032 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8033 }
8034 if (subject != null) {
8035 sb.append("Subject: ").append(subject).append("\n");
8036 }
8037 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008038 if (Debug.isDebuggerConnected()) {
8039 sb.append("Debugger: Connected\n");
8040 }
Dan Egnora455d192010-03-12 08:52:28 -08008041 sb.append("\n");
8042
8043 // Do the rest in a worker thread to avoid blocking the caller on I/O
8044 // (After this point, we shouldn't access AMS internal data structures.)
8045 Thread worker = new Thread("Error dump: " + dropboxTag) {
8046 @Override
8047 public void run() {
8048 if (report != null) {
8049 sb.append(report);
8050 }
8051 if (logFile != null) {
8052 try {
8053 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8054 } catch (IOException e) {
8055 Slog.e(TAG, "Error reading " + logFile, e);
8056 }
8057 }
8058 if (crashInfo != null && crashInfo.stackTrace != null) {
8059 sb.append(crashInfo.stackTrace);
8060 }
8061
8062 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8063 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8064 if (lines > 0) {
8065 sb.append("\n");
8066
8067 // Merge several logcat streams, and take the last N lines
8068 InputStreamReader input = null;
8069 try {
8070 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8071 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8072 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8073
8074 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8075 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8076 input = new InputStreamReader(logcat.getInputStream());
8077
8078 int num;
8079 char[] buf = new char[8192];
8080 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8081 } catch (IOException e) {
8082 Slog.e(TAG, "Error running logcat", e);
8083 } finally {
8084 if (input != null) try { input.close(); } catch (IOException e) {}
8085 }
8086 }
8087
8088 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008089 }
Dan Egnora455d192010-03-12 08:52:28 -08008090 };
8091
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008092 if (process == null) {
8093 // If process is null, we are being called from some internal code
8094 // and may be about to die -- run this synchronously.
8095 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008096 } else {
8097 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008098 }
8099 }
8100
8101 /**
8102 * Bring up the "unexpected error" dialog box for a crashing app.
8103 * Deal with edge cases (intercepts from instrumented applications,
8104 * ActivityController, error intent receivers, that sort of thing).
8105 * @param r the application crashing
8106 * @param crashInfo describing the failure
8107 */
8108 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008109 long timeMillis = System.currentTimeMillis();
8110 String shortMsg = crashInfo.exceptionClassName;
8111 String longMsg = crashInfo.exceptionMessage;
8112 String stackTrace = crashInfo.stackTrace;
8113 if (shortMsg != null && longMsg != null) {
8114 longMsg = shortMsg + ": " + longMsg;
8115 } else if (shortMsg != null) {
8116 longMsg = shortMsg;
8117 }
8118
Dan Egnor60d87622009-12-16 16:32:58 -08008119 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008121 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 try {
8123 String name = r != null ? r.processName : null;
8124 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008125 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008126 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008127 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 + " at watcher's request");
8129 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008130 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 }
8132 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008133 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 }
8135 }
8136
8137 final long origId = Binder.clearCallingIdentity();
8138
8139 // If this process is running instrumentation, finish it.
8140 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008141 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008142 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008143 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8144 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 Bundle info = new Bundle();
8146 info.putString("shortMsg", shortMsg);
8147 info.putString("longMsg", longMsg);
8148 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8149 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008150 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 }
8152
Dan Egnor60d87622009-12-16 16:32:58 -08008153 // If we can't identify the process or it's already exceeded its crash quota,
8154 // quit right away without showing a crash dialog.
8155 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008157 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 }
8159
8160 Message msg = Message.obtain();
8161 msg.what = SHOW_ERROR_MSG;
8162 HashMap data = new HashMap();
8163 data.put("result", result);
8164 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 msg.obj = data;
8166 mHandler.sendMessage(msg);
8167
8168 Binder.restoreCallingIdentity(origId);
8169 }
8170
8171 int res = result.get();
8172
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008173 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008175 if (r != null && !r.isolated) {
8176 // XXX Can't keep track of crash time for isolated processes,
8177 // since they don't have a persistent identity.
8178 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 SystemClock.uptimeMillis());
8180 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008181 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008182 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008183 }
8184 }
8185
8186 if (appErrorIntent != null) {
8187 try {
8188 mContext.startActivity(appErrorIntent);
8189 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008190 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008194
8195 Intent createAppErrorIntentLocked(ProcessRecord r,
8196 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8197 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008198 if (report == null) {
8199 return null;
8200 }
8201 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8202 result.setComponent(r.errorReportReceiver);
8203 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8204 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8205 return result;
8206 }
8207
Dan Egnorb7f03672009-12-09 16:22:32 -08008208 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8209 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008210 if (r.errorReportReceiver == null) {
8211 return null;
8212 }
8213
8214 if (!r.crashing && !r.notResponding) {
8215 return null;
8216 }
8217
Dan Egnorb7f03672009-12-09 16:22:32 -08008218 ApplicationErrorReport report = new ApplicationErrorReport();
8219 report.packageName = r.info.packageName;
8220 report.installerPackageName = r.errorReportReceiver.getPackageName();
8221 report.processName = r.processName;
8222 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008223 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008224
Dan Egnorb7f03672009-12-09 16:22:32 -08008225 if (r.crashing) {
8226 report.type = ApplicationErrorReport.TYPE_CRASH;
8227 report.crashInfo = crashInfo;
8228 } else if (r.notResponding) {
8229 report.type = ApplicationErrorReport.TYPE_ANR;
8230 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008231
Dan Egnorb7f03672009-12-09 16:22:32 -08008232 report.anrInfo.activity = r.notRespondingReport.tag;
8233 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8234 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008235 }
8236
Dan Egnorb7f03672009-12-09 16:22:32 -08008237 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008238 }
8239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008241 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008242 // assume our apps are happy - lazy create the list
8243 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8244
8245 synchronized (this) {
8246
8247 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008248 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8249 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008250 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8251 // This one's in trouble, so we'll generate a report for it
8252 // crashes are higher priority (in case there's a crash *and* an anr)
8253 ActivityManager.ProcessErrorStateInfo report = null;
8254 if (app.crashing) {
8255 report = app.crashingReport;
8256 } else if (app.notResponding) {
8257 report = app.notRespondingReport;
8258 }
8259
8260 if (report != null) {
8261 if (errList == null) {
8262 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8263 }
8264 errList.add(report);
8265 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008266 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 " crashing = " + app.crashing +
8268 " notResponding = " + app.notResponding);
8269 }
8270 }
8271 }
8272 }
8273
8274 return errList;
8275 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008276
8277 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008278 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008279 if (currApp != null) {
8280 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8281 }
8282 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008283 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8284 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008285 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8286 if (currApp != null) {
8287 currApp.lru = 0;
8288 }
8289 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008290 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008291 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8292 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8293 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8294 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8295 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8296 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8297 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8298 } else {
8299 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8300 }
8301 }
8302
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008303 private void fillInProcMemInfo(ProcessRecord app,
8304 ActivityManager.RunningAppProcessInfo outInfo) {
8305 outInfo.pid = app.pid;
8306 outInfo.uid = app.info.uid;
8307 if (mHeavyWeightProcess == app) {
8308 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8309 }
8310 if (app.persistent) {
8311 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8312 }
8313 outInfo.lastTrimLevel = app.trimMemoryLevel;
8314 int adj = app.curAdj;
8315 outInfo.importance = oomAdjToImportance(adj, outInfo);
8316 outInfo.importanceReasonCode = app.adjTypeCode;
8317 }
8318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008319 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008320 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008321 // Lazy instantiation of list
8322 List<ActivityManager.RunningAppProcessInfo> runList = null;
8323 synchronized (this) {
8324 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008325 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8326 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008327 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8328 // Generate process state info for running application
8329 ActivityManager.RunningAppProcessInfo currApp =
8330 new ActivityManager.RunningAppProcessInfo(app.processName,
8331 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008332 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008333 if (app.adjSource instanceof ProcessRecord) {
8334 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008335 currApp.importanceReasonImportance = oomAdjToImportance(
8336 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008337 } else if (app.adjSource instanceof ActivityRecord) {
8338 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008339 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8340 }
8341 if (app.adjTarget instanceof ComponentName) {
8342 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8343 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008344 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345 // + " lru=" + currApp.lru);
8346 if (runList == null) {
8347 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8348 }
8349 runList.add(currApp);
8350 }
8351 }
8352 }
8353 return runList;
8354 }
8355
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008356 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008357 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008358 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8359 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8360 if (runningApps != null && runningApps.size() > 0) {
8361 Set<String> extList = new HashSet<String>();
8362 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8363 if (app.pkgList != null) {
8364 for (String pkg : app.pkgList) {
8365 extList.add(pkg);
8366 }
8367 }
8368 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008369 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008370 for (String pkg : extList) {
8371 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008372 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008373 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8374 retList.add(info);
8375 }
8376 } catch (RemoteException e) {
8377 }
8378 }
8379 }
8380 return retList;
8381 }
8382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008384 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8385 enforceNotIsolatedCaller("getMyMemoryState");
8386 synchronized (this) {
8387 ProcessRecord proc;
8388 synchronized (mPidsSelfLocked) {
8389 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8390 }
8391 fillInProcMemInfo(proc, outInfo);
8392 }
8393 }
8394
8395 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008397 if (checkCallingPermission(android.Manifest.permission.DUMP)
8398 != PackageManager.PERMISSION_GRANTED) {
8399 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8400 + Binder.getCallingPid()
8401 + ", uid=" + Binder.getCallingUid()
8402 + " without permission "
8403 + android.Manifest.permission.DUMP);
8404 return;
8405 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008406
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008407 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008408 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008409 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008410
8411 int opti = 0;
8412 while (opti < args.length) {
8413 String opt = args[opti];
8414 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8415 break;
8416 }
8417 opti++;
8418 if ("-a".equals(opt)) {
8419 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008420 } else if ("-c".equals(opt)) {
8421 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008422 } else if ("-h".equals(opt)) {
8423 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008424 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008425 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008426 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008427 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8428 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8429 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008430 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008431 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008432 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008433 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008434 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008435 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008436 pw.println(" all: dump all activities");
8437 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008438 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008439 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8440 pw.println(" a partial substring in a component name, a");
8441 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008442 pw.println(" -a: include all available server state.");
8443 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008444 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008445 } else {
8446 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008448 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008449
8450 long origId = Binder.clearCallingIdentity();
8451 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008452 // Is the caller requesting to dump a particular piece of data?
8453 if (opti < args.length) {
8454 String cmd = args[opti];
8455 opti++;
8456 if ("activities".equals(cmd) || "a".equals(cmd)) {
8457 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008458 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008460 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008461 String[] newArgs;
8462 String name;
8463 if (opti >= args.length) {
8464 name = null;
8465 newArgs = EMPTY_STRING_ARRAY;
8466 } else {
8467 name = args[opti];
8468 opti++;
8469 newArgs = new String[args.length - opti];
8470 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8471 args.length - opti);
8472 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008473 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008474 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008476 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008477 String[] newArgs;
8478 String name;
8479 if (opti >= args.length) {
8480 name = null;
8481 newArgs = EMPTY_STRING_ARRAY;
8482 } else {
8483 name = args[opti];
8484 opti++;
8485 newArgs = new String[args.length - opti];
8486 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8487 args.length - opti);
8488 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008490 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008491 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008492 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008493 String[] newArgs;
8494 String name;
8495 if (opti >= args.length) {
8496 name = null;
8497 newArgs = EMPTY_STRING_ARRAY;
8498 } else {
8499 name = args[opti];
8500 opti++;
8501 newArgs = new String[args.length - opti];
8502 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8503 args.length - opti);
8504 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008505 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008506 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008508 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8509 synchronized (this) {
8510 dumpOomLocked(fd, pw, args, opti, true);
8511 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008512 } else if ("provider".equals(cmd)) {
8513 String[] newArgs;
8514 String name;
8515 if (opti >= args.length) {
8516 name = null;
8517 newArgs = EMPTY_STRING_ARRAY;
8518 } else {
8519 name = args[opti];
8520 opti++;
8521 newArgs = new String[args.length - opti];
8522 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8523 }
8524 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8525 pw.println("No providers match: " + name);
8526 pw.println("Use -h for help.");
8527 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008528 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8529 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008530 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008531 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008532 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008533 String[] newArgs;
8534 String name;
8535 if (opti >= args.length) {
8536 name = null;
8537 newArgs = EMPTY_STRING_ARRAY;
8538 } else {
8539 name = args[opti];
8540 opti++;
8541 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008542 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8543 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008544 }
8545 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8546 pw.println("No services match: " + name);
8547 pw.println("Use -h for help.");
8548 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008549 } else if ("package".equals(cmd)) {
8550 String[] newArgs;
8551 if (opti >= args.length) {
8552 pw.println("package: no package name specified");
8553 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008554 } else {
8555 dumpPackage = args[opti];
8556 opti++;
8557 newArgs = new String[args.length - opti];
8558 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8559 args.length - opti);
8560 args = newArgs;
8561 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008562 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008563 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008564 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8565 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008566 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008567 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008568 } else {
8569 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008570 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8571 pw.println("Bad activity command, or no activities match: " + cmd);
8572 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008573 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008574 }
8575 if (!more) {
8576 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008577 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008578 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008579 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008580
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581 // No piece of data specified, dump everything.
8582 synchronized (this) {
8583 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008584 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585 if (needSep) {
8586 pw.println(" ");
8587 }
8588 if (dumpAll) {
8589 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008590 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008591 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008592 if (needSep) {
8593 pw.println(" ");
8594 }
8595 if (dumpAll) {
8596 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008597 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008598 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 if (needSep) {
8600 pw.println(" ");
8601 }
8602 if (dumpAll) {
8603 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008604 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008605 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008606 if (needSep) {
8607 pw.println(" ");
8608 }
8609 if (dumpAll) {
8610 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008611 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008612 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008613 if (needSep) {
8614 pw.println(" ");
8615 }
8616 if (dumpAll) {
8617 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008618 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008619 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008620 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008621 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008622 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008623
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008624 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008625 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008626 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8627 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008628 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8629 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008630 pw.println(" ");
8631 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008632 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8633 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008634 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008636 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008637 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008638 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008639 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008640 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008642 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008643 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008644 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008645 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008646 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8647 pw.println(" ");
8648 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008649 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008650 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008651 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008652 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008653 pw.println(" ");
8654 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008655 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008656 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008660 if (mMainStack.mPausingActivity != null) {
8661 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008662 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008663 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008664 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008665 if (dumpAll) {
8666 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8667 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008668 pw.println(" mDismissKeyguardOnNextActivity: "
8669 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008672 if (mRecentTasks.size() > 0) {
8673 pw.println();
8674 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008675
8676 final int N = mRecentTasks.size();
8677 for (int i=0; i<N; i++) {
8678 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008679 if (dumpPackage != null) {
8680 if (tr.realActivity == null ||
8681 !dumpPackage.equals(tr.realActivity)) {
8682 continue;
8683 }
8684 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008685 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8686 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008687 if (dumpAll) {
8688 mRecentTasks.get(i).dump(pw, " ");
8689 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008690 }
8691 }
8692
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008693 if (dumpAll) {
8694 pw.println(" ");
8695 pw.println(" mCurTask: " + mCurTask);
8696 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008697
8698 return true;
8699 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008700
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008701 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008702 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008703 boolean needSep = false;
8704 int numPers = 0;
8705
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008706 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8707
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8710 final int NA = procs.size();
8711 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008712 ProcessRecord r = procs.valueAt(ia);
8713 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8714 continue;
8715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 if (!needSep) {
8717 pw.println(" All known processes:");
8718 needSep = true;
8719 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008720 pw.print(r.persistent ? " *PERS*" : " *APP*");
8721 pw.print(" UID "); pw.print(procs.keyAt(ia));
8722 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 r.dump(pw, " ");
8724 if (r.persistent) {
8725 numPers++;
8726 }
8727 }
8728 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008729 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008730
8731 if (mIsolatedProcesses.size() > 0) {
8732 if (needSep) pw.println(" ");
8733 needSep = true;
8734 pw.println(" Isolated process list (sorted by uid):");
8735 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8736 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8737 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8738 continue;
8739 }
8740 pw.println(String.format("%sIsolated #%2d: %s",
8741 " ", i, r.toString()));
8742 }
8743 }
8744
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008745 if (mLruProcesses.size() > 0) {
8746 if (needSep) pw.println(" ");
8747 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008748 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008749 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008750 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 needSep = true;
8752 }
8753
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008754 if (dumpAll) {
8755 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008756 boolean printed = false;
8757 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8758 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8759 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8760 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008761 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008762 if (!printed) {
8763 if (needSep) pw.println(" ");
8764 needSep = true;
8765 pw.println(" PID mappings:");
8766 printed = true;
8767 }
8768 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8769 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 }
8771 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008772 }
8773
8774 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008775 synchronized (mPidsSelfLocked) {
8776 boolean printed = false;
8777 for (int i=0; i<mForegroundProcesses.size(); i++) {
8778 ProcessRecord r = mPidsSelfLocked.get(
8779 mForegroundProcesses.valueAt(i).pid);
8780 if (dumpPackage != null && (r == null
8781 || !dumpPackage.equals(r.info.packageName))) {
8782 continue;
8783 }
8784 if (!printed) {
8785 if (needSep) pw.println(" ");
8786 needSep = true;
8787 pw.println(" Foreground Processes:");
8788 printed = true;
8789 }
8790 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8791 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008794 }
8795
8796 if (mPersistentStartingProcesses.size() > 0) {
8797 if (needSep) pw.println(" ");
8798 needSep = true;
8799 pw.println(" Persisent processes that are starting:");
8800 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008801 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008804 if (mRemovedProcesses.size() > 0) {
8805 if (needSep) pw.println(" ");
8806 needSep = true;
8807 pw.println(" Processes that are being removed:");
8808 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008809 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810 }
8811
8812 if (mProcessesOnHold.size() > 0) {
8813 if (needSep) pw.println(" ");
8814 needSep = true;
8815 pw.println(" Processes that are on old until the system is ready:");
8816 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008817 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008819
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008820 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008821
8822 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008823 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008824 long now = SystemClock.uptimeMillis();
8825 for (Map.Entry<String, SparseArray<Long>> procs
8826 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008827 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008828 SparseArray<Long> uids = procs.getValue();
8829 final int N = uids.size();
8830 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008831 int puid = uids.keyAt(i);
8832 ProcessRecord r = mProcessNames.get(pname, puid);
8833 if (dumpPackage != null && (r == null
8834 || !dumpPackage.equals(r.info.packageName))) {
8835 continue;
8836 }
8837 if (!printed) {
8838 if (needSep) pw.println(" ");
8839 needSep = true;
8840 pw.println(" Time since processes crashed:");
8841 printed = true;
8842 }
8843 pw.print(" Process "); pw.print(pname);
8844 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008846 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8847 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008848 }
8849 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008853 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008854 for (Map.Entry<String, SparseArray<Long>> procs
8855 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008856 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008857 SparseArray<Long> uids = procs.getValue();
8858 final int N = uids.size();
8859 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008860 int puid = uids.keyAt(i);
8861 ProcessRecord r = mProcessNames.get(pname, puid);
8862 if (dumpPackage != null && (r == null
8863 || !dumpPackage.equals(r.info.packageName))) {
8864 continue;
8865 }
8866 if (!printed) {
8867 if (needSep) pw.println(" ");
8868 needSep = true;
8869 pw.println(" Bad processes:");
8870 }
8871 pw.print(" Bad process "); pw.print(pname);
8872 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008873 pw.print(": crashed at time ");
8874 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 }
8876 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008879 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008880 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008881 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008882 if (dumpAll) {
8883 StringBuilder sb = new StringBuilder(128);
8884 sb.append(" mPreviousProcessVisibleTime: ");
8885 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8886 pw.println(sb);
8887 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008888 if (mHeavyWeightProcess != null) {
8889 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8890 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008891 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008892 if (dumpAll) {
8893 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008894 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008895 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008896 for (Map.Entry<String, Integer> entry
8897 : mCompatModePackages.getPackages().entrySet()) {
8898 String pkg = entry.getKey();
8899 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008900 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8901 continue;
8902 }
8903 if (!printed) {
8904 pw.println(" mScreenCompatPackages:");
8905 printed = true;
8906 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008907 pw.print(" "); pw.print(pkg); pw.print(": ");
8908 pw.print(mode); pw.println();
8909 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008910 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008911 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008912 if (mSleeping || mWentToSleep || mLockScreenShown) {
8913 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8914 + " mLockScreenShown " + mLockScreenShown);
8915 }
8916 if (mShuttingDown) {
8917 pw.println(" mShuttingDown=" + mShuttingDown);
8918 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008919 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8920 || mOrigWaitForDebugger) {
8921 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8922 + " mDebugTransient=" + mDebugTransient
8923 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8924 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008925 if (mOpenGlTraceApp != null) {
8926 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8927 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008928 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8929 || mProfileFd != null) {
8930 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8931 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8932 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8933 + mAutoStopProfiler);
8934 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 if (mAlwaysFinishActivities || mController != null) {
8936 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8937 + " mController=" + mController);
8938 }
8939 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008942 + " mProcessesReady=" + mProcessesReady
8943 + " mSystemReady=" + mSystemReady);
8944 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 + " mBooted=" + mBooted
8946 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008947 pw.print(" mLastPowerCheckRealtime=");
8948 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8949 pw.println("");
8950 pw.print(" mLastPowerCheckUptime=");
8951 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8952 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008953 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8954 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008955 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008956 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8957 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008959
8960 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 }
8962
Dianne Hackborn287952c2010-09-22 22:34:31 -07008963 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008964 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008965 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008966 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008967 long now = SystemClock.uptimeMillis();
8968 for (int i=0; i<mProcessesToGc.size(); i++) {
8969 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008970 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8971 continue;
8972 }
8973 if (!printed) {
8974 if (needSep) pw.println(" ");
8975 needSep = true;
8976 pw.println(" Processes that are waiting to GC:");
8977 printed = true;
8978 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008979 pw.print(" Process "); pw.println(proc);
8980 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8981 pw.print(", last gced=");
8982 pw.print(now-proc.lastRequestedGc);
8983 pw.print(" ms ago, last lowMem=");
8984 pw.print(now-proc.lastLowMemory);
8985 pw.println(" ms ago");
8986
8987 }
8988 }
8989 return needSep;
8990 }
8991
8992 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8993 int opti, boolean dumpAll) {
8994 boolean needSep = false;
8995
8996 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008997 if (needSep) pw.println(" ");
8998 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008999 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009000 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009001 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009002 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9003 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9004 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9005 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9006 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009007 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009008 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009009 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009010 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009011 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009012 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009013
9014 if (needSep) pw.println(" ");
9015 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009016 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009017 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009018 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009019 needSep = true;
9020 }
9021
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009022 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009023
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009024 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009025 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009026 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009027 if (mHeavyWeightProcess != null) {
9028 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9029 }
9030
9031 return true;
9032 }
9033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 /**
9035 * There are three ways to call this:
9036 * - no service specified: dump all the services
9037 * - a flattened component name that matched an existing service was specified as the
9038 * first arg: dump that one service
9039 * - the first arg isn't the flattened component name of an existing service:
9040 * dump all services whose component contains the first arg as a substring
9041 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009042 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9043 int opti, boolean dumpAll) {
9044 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009046 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009047 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009048 try {
9049 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9050 for (UserInfo user : users) {
9051 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9052 services.add(r1);
9053 }
9054 }
9055 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009056 }
9057 }
9058 } else {
9059 ComponentName componentName = name != null
9060 ? ComponentName.unflattenFromString(name) : null;
9061 int objectId = 0;
9062 if (componentName == null) {
9063 // Not a '/' separated full component name; maybe an object ID?
9064 try {
9065 objectId = Integer.parseInt(name, 16);
9066 name = null;
9067 componentName = null;
9068 } catch (RuntimeException e) {
9069 }
9070 }
9071
9072 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009073 try {
9074 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9075 for (UserInfo user : users) {
9076 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9077 if (componentName != null) {
9078 if (r1.name.equals(componentName)) {
9079 services.add(r1);
9080 }
9081 } else if (name != null) {
9082 if (r1.name.flattenToString().contains(name)) {
9083 services.add(r1);
9084 }
9085 } else if (System.identityHashCode(r1) == objectId) {
9086 services.add(r1);
9087 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009088 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009089 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009090 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 }
9092 }
9093 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009094
9095 if (services.size() <= 0) {
9096 return false;
9097 }
9098
9099 boolean needSep = false;
9100 for (int i=0; i<services.size(); i++) {
9101 if (needSep) {
9102 pw.println();
9103 }
9104 needSep = true;
9105 dumpService("", fd, pw, services.get(i), args, dumpAll);
9106 }
9107 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 }
9109
9110 /**
9111 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9112 * there is a thread associated with the service.
9113 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009114 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9115 final ServiceRecord r, String[] args, boolean dumpAll) {
9116 String innerPrefix = prefix + " ";
9117 synchronized (this) {
9118 pw.print(prefix); pw.print("SERVICE ");
9119 pw.print(r.shortName); pw.print(" ");
9120 pw.print(Integer.toHexString(System.identityHashCode(r)));
9121 pw.print(" pid=");
9122 if (r.app != null) pw.println(r.app.pid);
9123 else pw.println("(not running)");
9124 if (dumpAll) {
9125 r.dump(pw, innerPrefix);
9126 }
9127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009128 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009129 pw.print(prefix); pw.println(" Client:");
9130 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009131 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009132 TransferPipe tp = new TransferPipe();
9133 try {
9134 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9135 tp.setBufferPrefix(prefix + " ");
9136 tp.go(fd);
9137 } finally {
9138 tp.kill();
9139 }
9140 } catch (IOException e) {
9141 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009143 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009144 }
9145 }
9146 }
9147
Marco Nelissen18cb2872011-11-15 11:19:53 -08009148 /**
9149 * There are three ways to call this:
9150 * - no provider specified: dump all the providers
9151 * - a flattened component name that matched an existing provider was specified as the
9152 * first arg: dump that one provider
9153 * - the first arg isn't the flattened component name of an existing provider:
9154 * dump all providers whose component contains the first arg as a substring
9155 */
9156 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9157 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009158 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009159 }
9160
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009161 static class ItemMatcher {
9162 ArrayList<ComponentName> components;
9163 ArrayList<String> strings;
9164 ArrayList<Integer> objects;
9165 boolean all;
9166
9167 ItemMatcher() {
9168 all = true;
9169 }
9170
9171 void build(String name) {
9172 ComponentName componentName = ComponentName.unflattenFromString(name);
9173 if (componentName != null) {
9174 if (components == null) {
9175 components = new ArrayList<ComponentName>();
9176 }
9177 components.add(componentName);
9178 all = false;
9179 } else {
9180 int objectId = 0;
9181 // Not a '/' separated full component name; maybe an object ID?
9182 try {
9183 objectId = Integer.parseInt(name, 16);
9184 if (objects == null) {
9185 objects = new ArrayList<Integer>();
9186 }
9187 objects.add(objectId);
9188 all = false;
9189 } catch (RuntimeException e) {
9190 // Not an integer; just do string match.
9191 if (strings == null) {
9192 strings = new ArrayList<String>();
9193 }
9194 strings.add(name);
9195 all = false;
9196 }
9197 }
9198 }
9199
9200 int build(String[] args, int opti) {
9201 for (; opti<args.length; opti++) {
9202 String name = args[opti];
9203 if ("--".equals(name)) {
9204 return opti+1;
9205 }
9206 build(name);
9207 }
9208 return opti;
9209 }
9210
9211 boolean match(Object object, ComponentName comp) {
9212 if (all) {
9213 return true;
9214 }
9215 if (components != null) {
9216 for (int i=0; i<components.size(); i++) {
9217 if (components.get(i).equals(comp)) {
9218 return true;
9219 }
9220 }
9221 }
9222 if (objects != null) {
9223 for (int i=0; i<objects.size(); i++) {
9224 if (System.identityHashCode(object) == objects.get(i)) {
9225 return true;
9226 }
9227 }
9228 }
9229 if (strings != null) {
9230 String flat = comp.flattenToString();
9231 for (int i=0; i<strings.size(); i++) {
9232 if (flat.contains(strings.get(i))) {
9233 return true;
9234 }
9235 }
9236 }
9237 return false;
9238 }
9239 }
9240
Dianne Hackborn625ac272010-09-17 18:29:22 -07009241 /**
9242 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009243 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009244 * - the cmd arg isn't the flattened component name of an existing activity:
9245 * dump all activity whose component contains the cmd as a substring
9246 * - A hex number of the ActivityRecord object instance.
9247 */
9248 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9249 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009250 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009251
9252 if ("all".equals(name)) {
9253 synchronized (this) {
9254 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009255 activities.add(r1);
9256 }
9257 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009258 } else if ("top".equals(name)) {
9259 synchronized (this) {
9260 final int N = mMainStack.mHistory.size();
9261 if (N > 0) {
9262 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9263 }
9264 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009265 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009266 ItemMatcher matcher = new ItemMatcher();
9267 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009268
9269 synchronized (this) {
9270 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009271 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009272 activities.add(r1);
9273 }
9274 }
9275 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009276 }
9277
9278 if (activities.size() <= 0) {
9279 return false;
9280 }
9281
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009282 String[] newArgs = new String[args.length - opti];
9283 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9284
Dianne Hackborn30d71892010-12-11 10:37:55 -08009285 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009286 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009287 for (int i=activities.size()-1; i>=0; i--) {
9288 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009289 if (needSep) {
9290 pw.println();
9291 }
9292 needSep = true;
9293 synchronized (this) {
9294 if (lastTask != r.task) {
9295 lastTask = r.task;
9296 pw.print("TASK "); pw.print(lastTask.affinity);
9297 pw.print(" id="); pw.println(lastTask.taskId);
9298 if (dumpAll) {
9299 lastTask.dump(pw, " ");
9300 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009301 }
9302 }
9303 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009304 }
9305 return true;
9306 }
9307
9308 /**
9309 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9310 * there is a thread associated with the activity.
9311 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009312 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009313 final ActivityRecord r, String[] args, boolean dumpAll) {
9314 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009315 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009316 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9317 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9318 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009319 if (r.app != null) pw.println(r.app.pid);
9320 else pw.println("(not running)");
9321 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009322 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009323 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009324 }
9325 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009326 // flush anything that is already in the PrintWriter since the thread is going
9327 // to write to the file descriptor directly
9328 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009329 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009330 TransferPipe tp = new TransferPipe();
9331 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009332 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9333 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009334 tp.go(fd);
9335 } finally {
9336 tp.kill();
9337 }
9338 } catch (IOException e) {
9339 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009340 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009341 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009342 }
9343 }
9344 }
9345
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009346 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009347 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009348 boolean needSep = false;
9349
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009350 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009351 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009353 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009354 Iterator it = mRegisteredReceivers.values().iterator();
9355 while (it.hasNext()) {
9356 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009357 if (dumpPackage != null && (r.app == null ||
9358 !dumpPackage.equals(r.app.info.packageName))) {
9359 continue;
9360 }
9361 if (!printed) {
9362 pw.println(" Registered Receivers:");
9363 needSep = true;
9364 printed = true;
9365 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009366 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 r.dump(pw, " ");
9368 }
9369 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009370
9371 if (mReceiverResolver.dump(pw, needSep ?
9372 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9373 " ", dumpPackage, false)) {
9374 needSep = true;
9375 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009376 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009377
9378 for (BroadcastQueue q : mBroadcastQueues) {
9379 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009382 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009383
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009384 if (mStickyBroadcasts != null && dumpPackage == null) {
9385 if (needSep) {
9386 pw.println();
9387 }
9388 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009389 pw.println(" Sticky broadcasts:");
9390 StringBuilder sb = new StringBuilder(128);
9391 for (Map.Entry<String, ArrayList<Intent>> ent
9392 : mStickyBroadcasts.entrySet()) {
9393 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009394 if (dumpAll) {
9395 pw.println(":");
9396 ArrayList<Intent> intents = ent.getValue();
9397 final int N = intents.size();
9398 for (int i=0; i<N; i++) {
9399 sb.setLength(0);
9400 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009401 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009402 pw.println(sb.toString());
9403 Bundle bundle = intents.get(i).getExtras();
9404 if (bundle != null) {
9405 pw.print(" ");
9406 pw.println(bundle.toString());
9407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009409 } else {
9410 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 }
9412 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009413 needSep = true;
9414 }
9415
9416 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009417 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009418 for (BroadcastQueue queue : mBroadcastQueues) {
9419 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9420 + queue.mBroadcastsScheduled);
9421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422 pw.println(" mHandler:");
9423 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009424 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009426
9427 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 }
9429
Marco Nelissen18cb2872011-11-15 11:19:53 -08009430 /**
9431 * Prints a list of ServiceRecords (dumpsys activity services)
9432 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009433 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009434 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009435 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009437 ItemMatcher matcher = new ItemMatcher();
9438 matcher.build(args, opti);
9439
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009440 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009441 try {
9442 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9443 for (UserInfo user : users) {
9444 if (mServiceMap.getAllServices(user.id).size() > 0) {
9445 boolean printed = false;
9446 long nowReal = SystemClock.elapsedRealtime();
9447 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9448 user.id).iterator();
9449 needSep = false;
9450 while (it.hasNext()) {
9451 ServiceRecord r = it.next();
9452 if (!matcher.match(r, r.name)) {
9453 continue;
9454 }
9455 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9456 continue;
9457 }
9458 if (!printed) {
9459 pw.println(" Active services:");
9460 printed = true;
9461 }
9462 if (needSep) {
9463 pw.println();
9464 }
9465 pw.print(" * ");
9466 pw.println(r);
9467 if (dumpAll) {
9468 r.dump(pw, " ");
9469 needSep = true;
9470 } else {
9471 pw.print(" app=");
9472 pw.println(r.app);
9473 pw.print(" created=");
9474 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9475 pw.print(" started=");
9476 pw.print(r.startRequested);
9477 pw.print(" connections=");
9478 pw.println(r.connections.size());
9479 if (r.connections.size() > 0) {
9480 pw.println(" Connections:");
9481 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9482 for (int i = 0; i < clist.size(); i++) {
9483 ConnectionRecord conn = clist.get(i);
9484 pw.print(" ");
9485 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009486 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009487 pw.print(" -> ");
9488 ProcessRecord proc = conn.binding.client;
9489 pw.println(proc != null ? proc.toShortString() : "null");
9490 }
9491 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009492 }
9493 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009494 if (dumpClient && r.app != null && r.app.thread != null) {
9495 pw.println(" Client:");
9496 pw.flush();
9497 try {
9498 TransferPipe tp = new TransferPipe();
9499 try {
9500 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9501 r, args);
9502 tp.setBufferPrefix(" ");
9503 // Short timeout, since blocking here can
9504 // deadlock with the application.
9505 tp.go(fd, 2000);
9506 } finally {
9507 tp.kill();
9508 }
9509 } catch (IOException e) {
9510 pw.println(" Failure while dumping the service: " + e);
9511 } catch (RemoteException e) {
9512 pw.println(" Got a RemoteException while dumping the service");
9513 }
9514 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009515 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009516 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009517 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009520 } catch (RemoteException re) {
9521
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009523
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009524 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009525 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009526 for (int i=0; i<mPendingServices.size(); i++) {
9527 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009528 if (!matcher.match(r, r.name)) {
9529 continue;
9530 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009531 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9532 continue;
9533 }
9534 if (!printed) {
9535 if (needSep) pw.println(" ");
9536 needSep = true;
9537 pw.println(" Pending services:");
9538 printed = true;
9539 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009540 pw.print(" * Pending "); pw.println(r);
9541 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009543 needSep = true;
9544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009545
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009546 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009547 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009548 for (int i=0; i<mRestartingServices.size(); i++) {
9549 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009550 if (!matcher.match(r, r.name)) {
9551 continue;
9552 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009553 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9554 continue;
9555 }
9556 if (!printed) {
9557 if (needSep) pw.println(" ");
9558 needSep = true;
9559 pw.println(" Restarting services:");
9560 printed = true;
9561 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009562 pw.print(" * Restarting "); pw.println(r);
9563 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009564 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009565 needSep = true;
9566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009567
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009568 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009569 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009570 for (int i=0; i<mStoppingServices.size(); i++) {
9571 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009572 if (!matcher.match(r, r.name)) {
9573 continue;
9574 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009575 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9576 continue;
9577 }
9578 if (!printed) {
9579 if (needSep) pw.println(" ");
9580 needSep = true;
9581 pw.println(" Stopping services:");
9582 printed = true;
9583 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009584 pw.print(" * Stopping "); pw.println(r);
9585 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009586 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009587 needSep = true;
9588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009589
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009590 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009592 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009593 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009594 = mServiceConnections.values().iterator();
9595 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009596 ArrayList<ConnectionRecord> r = it.next();
9597 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009598 ConnectionRecord cr = r.get(i);
9599 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9600 continue;
9601 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009602 if (dumpPackage != null && (cr.binding.client == null
9603 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9604 continue;
9605 }
9606 if (!printed) {
9607 if (needSep) pw.println(" ");
9608 needSep = true;
9609 pw.println(" Connection bindings to services:");
9610 printed = true;
9611 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009612 pw.print(" * "); pw.println(cr);
9613 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009616 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617 }
9618 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009619
9620 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009621 }
9622
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009623 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009624 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009625 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009626
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009627 ItemMatcher matcher = new ItemMatcher();
9628 matcher.build(args, opti);
9629
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009630 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009631
9632 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009633
9634 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009635 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009636 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009637 ContentProviderRecord r = mLaunchingProviders.get(i);
9638 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9639 continue;
9640 }
9641 if (!printed) {
9642 if (needSep) pw.println(" ");
9643 needSep = true;
9644 pw.println(" Launching content providers:");
9645 printed = true;
9646 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009647 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009648 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009649 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009650 }
9651
9652 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009653 if (needSep) pw.println();
9654 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009655 pw.println("Granted Uri Permissions:");
9656 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9657 int uid = mGrantedUriPermissions.keyAt(i);
9658 HashMap<Uri, UriPermission> perms
9659 = mGrantedUriPermissions.valueAt(i);
9660 pw.print(" * UID "); pw.print(uid);
9661 pw.println(" holds:");
9662 for (UriPermission perm : perms.values()) {
9663 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009664 if (dumpAll) {
9665 perm.dump(pw, " ");
9666 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009667 }
9668 }
9669 needSep = true;
9670 }
9671
9672 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 }
9674
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009675 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009676 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009677 boolean needSep = false;
9678
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009679 if (mIntentSenderRecords.size() > 0) {
9680 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009681 Iterator<WeakReference<PendingIntentRecord>> it
9682 = mIntentSenderRecords.values().iterator();
9683 while (it.hasNext()) {
9684 WeakReference<PendingIntentRecord> ref = it.next();
9685 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009686 if (dumpPackage != null && (rec == null
9687 || !dumpPackage.equals(rec.key.packageName))) {
9688 continue;
9689 }
9690 if (!printed) {
9691 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9692 printed = true;
9693 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009694 needSep = true;
9695 if (rec != null) {
9696 pw.print(" * "); pw.println(rec);
9697 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009698 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009700 } else {
9701 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702 }
9703 }
9704 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009705
9706 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009707 }
9708
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009709 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009710 String prefix, String label, boolean complete, boolean brief, boolean client,
9711 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009712 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009713 boolean needNL = false;
9714 final String innerPrefix = prefix + " ";
9715 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009716 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009717 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009718 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9719 continue;
9720 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009721 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009722 if (needNL) {
9723 pw.println(" ");
9724 needNL = false;
9725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726 if (lastTask != r.task) {
9727 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009728 pw.print(prefix);
9729 pw.print(full ? "* " : " ");
9730 pw.println(lastTask);
9731 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009732 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009733 } else if (complete) {
9734 // Complete + brief == give a summary. Isn't that obvious?!?
9735 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009736 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009737 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009738 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009740 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009741 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9742 pw.print(" #"); pw.print(i); pw.print(": ");
9743 pw.println(r);
9744 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009745 r.dump(pw, innerPrefix);
9746 } else if (complete) {
9747 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009748 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009749 if (r.app != null) {
9750 pw.print(innerPrefix); pw.println(r.app);
9751 }
9752 }
9753 if (client && r.app != null && r.app.thread != null) {
9754 // flush anything that is already in the PrintWriter since the thread is going
9755 // to write to the file descriptor directly
9756 pw.flush();
9757 try {
9758 TransferPipe tp = new TransferPipe();
9759 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009760 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9761 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009762 // Short timeout, since blocking here can
9763 // deadlock with the application.
9764 tp.go(fd, 2000);
9765 } finally {
9766 tp.kill();
9767 }
9768 } catch (IOException e) {
9769 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9770 } catch (RemoteException e) {
9771 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9772 }
9773 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009775 }
9776 }
9777
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009778 private static String buildOomTag(String prefix, String space, int val, int base) {
9779 if (val == base) {
9780 if (space == null) return prefix;
9781 return prefix + " ";
9782 }
9783 return prefix + "+" + Integer.toString(val-base);
9784 }
9785
9786 private static final int dumpProcessList(PrintWriter pw,
9787 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009788 String prefix, String normalLabel, String persistentLabel,
9789 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009790 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009791 final int N = list.size()-1;
9792 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009793 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009794 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9795 continue;
9796 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009797 pw.println(String.format("%s%s #%2d: %s",
9798 prefix, (r.persistent ? persistentLabel : normalLabel),
9799 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009800 if (r.persistent) {
9801 numPers++;
9802 }
9803 }
9804 return numPers;
9805 }
9806
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009807 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009808 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009809 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009810 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009811
Dianne Hackborn905577f2011-09-07 18:31:28 -07009812 ArrayList<Pair<ProcessRecord, Integer>> list
9813 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9814 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009815 ProcessRecord r = origList.get(i);
9816 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9817 continue;
9818 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009819 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9820 }
9821
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009822 if (list.size() <= 0) {
9823 return false;
9824 }
9825
Dianne Hackborn905577f2011-09-07 18:31:28 -07009826 Comparator<Pair<ProcessRecord, Integer>> comparator
9827 = new Comparator<Pair<ProcessRecord, Integer>>() {
9828 @Override
9829 public int compare(Pair<ProcessRecord, Integer> object1,
9830 Pair<ProcessRecord, Integer> object2) {
9831 if (object1.first.setAdj != object2.first.setAdj) {
9832 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9833 }
9834 if (object1.second.intValue() != object2.second.intValue()) {
9835 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9836 }
9837 return 0;
9838 }
9839 };
9840
9841 Collections.sort(list, comparator);
9842
Dianne Hackborn287952c2010-09-22 22:34:31 -07009843 final long curRealtime = SystemClock.elapsedRealtime();
9844 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9845 final long curUptime = SystemClock.uptimeMillis();
9846 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9847
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009848 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009849 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009850 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009851 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009852 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009853 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9854 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009855 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9856 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009857 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9858 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009859 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9860 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009861 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009862 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009863 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9864 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9865 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9866 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9867 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9868 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9869 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9870 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009871 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9872 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009873 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9874 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009875 } else {
9876 oomAdj = Integer.toString(r.setAdj);
9877 }
9878 String schedGroup;
9879 switch (r.setSchedGroup) {
9880 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9881 schedGroup = "B";
9882 break;
9883 case Process.THREAD_GROUP_DEFAULT:
9884 schedGroup = "F";
9885 break;
9886 default:
9887 schedGroup = Integer.toString(r.setSchedGroup);
9888 break;
9889 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009890 String foreground;
9891 if (r.foregroundActivities) {
9892 foreground = "A";
9893 } else if (r.foregroundServices) {
9894 foreground = "S";
9895 } else {
9896 foreground = " ";
9897 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009898 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009899 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009900 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9901 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009902 if (r.adjSource != null || r.adjTarget != null) {
9903 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009904 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009905 if (r.adjTarget instanceof ComponentName) {
9906 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9907 } else if (r.adjTarget != null) {
9908 pw.print(r.adjTarget.toString());
9909 } else {
9910 pw.print("{null}");
9911 }
9912 pw.print("<=");
9913 if (r.adjSource instanceof ProcessRecord) {
9914 pw.print("Proc{");
9915 pw.print(((ProcessRecord)r.adjSource).toShortString());
9916 pw.println("}");
9917 } else if (r.adjSource != null) {
9918 pw.println(r.adjSource.toString());
9919 } else {
9920 pw.println("{null}");
9921 }
9922 }
9923 if (inclDetails) {
9924 pw.print(prefix);
9925 pw.print(" ");
9926 pw.print("oom: max="); pw.print(r.maxAdj);
9927 pw.print(" hidden="); pw.print(r.hiddenAdj);
9928 pw.print(" curRaw="); pw.print(r.curRawAdj);
9929 pw.print(" setRaw="); pw.print(r.setRawAdj);
9930 pw.print(" cur="); pw.print(r.curAdj);
9931 pw.print(" set="); pw.println(r.setAdj);
9932 pw.print(prefix);
9933 pw.print(" ");
9934 pw.print("keeping="); pw.print(r.keeping);
9935 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009936 pw.print(" empty="); pw.print(r.empty);
9937 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009938
9939 if (!r.keeping) {
9940 if (r.lastWakeTime != 0) {
9941 long wtime;
9942 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9943 synchronized (stats) {
9944 wtime = stats.getProcessWakeTime(r.info.uid,
9945 r.pid, curRealtime);
9946 }
9947 long timeUsed = wtime - r.lastWakeTime;
9948 pw.print(prefix);
9949 pw.print(" ");
9950 pw.print("keep awake over ");
9951 TimeUtils.formatDuration(realtimeSince, pw);
9952 pw.print(" used ");
9953 TimeUtils.formatDuration(timeUsed, pw);
9954 pw.print(" (");
9955 pw.print((timeUsed*100)/realtimeSince);
9956 pw.println("%)");
9957 }
9958 if (r.lastCpuTime != 0) {
9959 long timeUsed = r.curCpuTime - r.lastCpuTime;
9960 pw.print(prefix);
9961 pw.print(" ");
9962 pw.print("run cpu over ");
9963 TimeUtils.formatDuration(uptimeSince, pw);
9964 pw.print(" used ");
9965 TimeUtils.formatDuration(timeUsed, pw);
9966 pw.print(" (");
9967 pw.print((timeUsed*100)/uptimeSince);
9968 pw.println("%)");
9969 }
9970 }
9971 }
9972 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009973 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009974 }
9975
Dianne Hackbornb437e092011-08-05 17:50:29 -07009976 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009977 ArrayList<ProcessRecord> procs;
9978 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009979 if (args != null && args.length > start
9980 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009981 procs = new ArrayList<ProcessRecord>();
9982 int pid = -1;
9983 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009984 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009985 } catch (NumberFormatException e) {
9986
9987 }
9988 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9989 ProcessRecord proc = mLruProcesses.get(i);
9990 if (proc.pid == pid) {
9991 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009992 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009993 procs.add(proc);
9994 }
9995 }
9996 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009997 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009998 return null;
9999 }
10000 } else {
10001 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10002 }
10003 }
10004 return procs;
10005 }
10006
10007 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10008 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010009 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010010 if (procs == null) {
10011 return;
10012 }
10013
10014 long uptime = SystemClock.uptimeMillis();
10015 long realtime = SystemClock.elapsedRealtime();
10016 pw.println("Applications Graphics Acceleration Info:");
10017 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10018
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010019 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10020 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010021 if (r.thread != null) {
10022 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10023 pw.flush();
10024 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010025 TransferPipe tp = new TransferPipe();
10026 try {
10027 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10028 tp.go(fd);
10029 } finally {
10030 tp.kill();
10031 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010032 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010033 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010034 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010035 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010036 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010037 pw.flush();
10038 }
10039 }
10040 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010041 }
10042
Jeff Brown6754ba22011-12-14 20:20:01 -080010043 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10044 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10045 if (procs == null) {
10046 return;
10047 }
10048
10049 pw.println("Applications Database Info:");
10050
10051 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10052 ProcessRecord r = procs.get(i);
10053 if (r.thread != null) {
10054 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10055 pw.flush();
10056 try {
10057 TransferPipe tp = new TransferPipe();
10058 try {
10059 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10060 tp.go(fd);
10061 } finally {
10062 tp.kill();
10063 }
10064 } catch (IOException e) {
10065 pw.println("Failure while dumping the app: " + r);
10066 pw.flush();
10067 } catch (RemoteException e) {
10068 pw.println("Got a RemoteException while dumping the app " + r);
10069 pw.flush();
10070 }
10071 }
10072 }
10073 }
10074
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010075 final static class MemItem {
10076 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010077 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010078 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010079 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010080 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010081
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010082 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010083 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010084 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010085 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010086 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010087 }
10088 }
10089
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010090 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010091 boolean sort) {
10092 if (sort) {
10093 Collections.sort(items, new Comparator<MemItem>() {
10094 @Override
10095 public int compare(MemItem lhs, MemItem rhs) {
10096 if (lhs.pss < rhs.pss) {
10097 return 1;
10098 } else if (lhs.pss > rhs.pss) {
10099 return -1;
10100 }
10101 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010102 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010103 });
10104 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010105
10106 for (int i=0; i<items.size(); i++) {
10107 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010108 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010109 if (mi.subitems != null) {
10110 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10111 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010112 }
10113 }
10114
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010115 // These are in KB.
10116 static final long[] DUMP_MEM_BUCKETS = new long[] {
10117 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10118 120*1024, 160*1024, 200*1024,
10119 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10120 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10121 };
10122
Dianne Hackborn672342c2011-11-29 11:29:02 -080010123 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10124 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010125 int start = label.lastIndexOf('.');
10126 if (start >= 0) start++;
10127 else start = 0;
10128 int end = label.length();
10129 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10130 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10131 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10132 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010133 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010134 out.append(label, start, end);
10135 return;
10136 }
10137 }
10138 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010139 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010140 out.append(label, start, end);
10141 }
10142
10143 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10144 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10145 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10146 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10147 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10148 };
10149 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10150 "System", "Persistent", "Foreground",
10151 "Visible", "Perceptible", "Heavy Weight",
10152 "Backup", "A Services", "Home", "Previous",
10153 "B Services", "Background"
10154 };
10155
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010156 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010157 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010158 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010159 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010160 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010161
10162 int opti = 0;
10163 while (opti < args.length) {
10164 String opt = args[opti];
10165 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10166 break;
10167 }
10168 opti++;
10169 if ("-a".equals(opt)) {
10170 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010171 } else if ("--oom".equals(opt)) {
10172 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010173 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010174 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010175 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010176 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010177 pw.println("If [process] is specified it can be the name or ");
10178 pw.println("pid of a specific process to dump.");
10179 return;
10180 } else {
10181 pw.println("Unknown argument: " + opt + "; use -h for help");
10182 }
10183 }
10184
10185 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010186 if (procs == null) {
10187 return;
10188 }
10189
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010190 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010191 long uptime = SystemClock.uptimeMillis();
10192 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010193
10194 if (procs.size() == 1 || isCheckinRequest) {
10195 dumpAll = true;
10196 }
10197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010198 if (isCheckinRequest) {
10199 // short checkin version
10200 pw.println(uptime + "," + realtime);
10201 pw.flush();
10202 } else {
10203 pw.println("Applications Memory Usage (kB):");
10204 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10205 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010206
Dianne Hackbornb437e092011-08-05 17:50:29 -070010207 String[] innerArgs = new String[args.length-opti];
10208 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10209
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010210 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10211 long nativePss=0, dalvikPss=0, otherPss=0;
10212 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10213
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010214 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10215 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10216 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010217
10218 long totalPss = 0;
10219
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010220 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10221 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010222 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010223 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010224 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10225 pw.flush();
10226 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010227 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010228 if (dumpAll) {
10229 try {
10230 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10231 } catch (RemoteException e) {
10232 if (!isCheckinRequest) {
10233 pw.println("Got RemoteException!");
10234 pw.flush();
10235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010236 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010237 } else {
10238 mi = new Debug.MemoryInfo();
10239 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010240 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010241
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010242 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010243 long myTotalPss = mi.getTotalPss();
10244 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010245 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010246 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010247 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010248
10249 nativePss += mi.nativePss;
10250 dalvikPss += mi.dalvikPss;
10251 otherPss += mi.otherPss;
10252 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10253 long mem = mi.getOtherPss(j);
10254 miscPss[j] += mem;
10255 otherPss -= mem;
10256 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010257
10258 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010259 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10260 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010261 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010262 if (oomProcs[oomIndex] == null) {
10263 oomProcs[oomIndex] = new ArrayList<MemItem>();
10264 }
10265 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010266 break;
10267 }
10268 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 }
10271 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010272
10273 if (!isCheckinRequest && procs.size() > 1) {
10274 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10275
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010276 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10277 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10278 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010279 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010280 String label = Debug.MemoryInfo.getOtherLabel(j);
10281 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010282 }
10283
Dianne Hackbornb437e092011-08-05 17:50:29 -070010284 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10285 for (int j=0; j<oomPss.length; j++) {
10286 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010287 String label = DUMP_MEM_OOM_LABEL[j];
10288 MemItem item = new MemItem(label, label, oomPss[j],
10289 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010290 item.subitems = oomProcs[j];
10291 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010292 }
10293 }
10294
Dianne Hackborn672342c2011-11-29 11:29:02 -080010295 if (outTag != null || outStack != null) {
10296 if (outTag != null) {
10297 appendMemBucket(outTag, totalPss, "total", false);
10298 }
10299 if (outStack != null) {
10300 appendMemBucket(outStack, totalPss, "total", true);
10301 }
10302 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010303 for (int i=0; i<oomMems.size(); i++) {
10304 MemItem miCat = oomMems.get(i);
10305 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10306 continue;
10307 }
10308 if (miCat.id < ProcessList.SERVICE_ADJ
10309 || miCat.id == ProcessList.HOME_APP_ADJ
10310 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010311 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10312 outTag.append(" / ");
10313 }
10314 if (outStack != null) {
10315 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10316 if (firstLine) {
10317 outStack.append(":");
10318 firstLine = false;
10319 }
10320 outStack.append("\n\t at ");
10321 } else {
10322 outStack.append("$");
10323 }
10324 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010325 for (int j=0; j<miCat.subitems.size(); j++) {
10326 MemItem mi = miCat.subitems.get(j);
10327 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010328 if (outTag != null) {
10329 outTag.append(" ");
10330 }
10331 if (outStack != null) {
10332 outStack.append("$");
10333 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010334 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010335 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10336 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10337 }
10338 if (outStack != null) {
10339 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10340 }
10341 }
10342 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10343 outStack.append("(");
10344 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10345 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10346 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10347 outStack.append(":");
10348 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10349 }
10350 }
10351 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010352 }
10353 }
10354 }
10355 }
10356
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010357 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010358 pw.println();
10359 pw.println("Total PSS by process:");
10360 dumpMemItems(pw, " ", procMems, true);
10361 pw.println();
10362 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010363 pw.println("Total PSS by OOM adjustment:");
10364 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010365 if (!oomOnly) {
10366 PrintWriter out = categoryPw != null ? categoryPw : pw;
10367 out.println();
10368 out.println("Total PSS by category:");
10369 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010370 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010371 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010372 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010373 final int[] SINGLE_LONG_FORMAT = new int[] {
10374 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10375 };
10376 long[] longOut = new long[1];
10377 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10378 SINGLE_LONG_FORMAT, null, longOut, null);
10379 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10380 longOut[0] = 0;
10381 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10382 SINGLE_LONG_FORMAT, null, longOut, null);
10383 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10384 longOut[0] = 0;
10385 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10386 SINGLE_LONG_FORMAT, null, longOut, null);
10387 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10388 longOut[0] = 0;
10389 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10390 SINGLE_LONG_FORMAT, null, longOut, null);
10391 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10392 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10393 pw.print(shared); pw.println(" kB");
10394 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10395 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 }
10398
10399 /**
10400 * Searches array of arguments for the specified string
10401 * @param args array of argument strings
10402 * @param value value to search for
10403 * @return true if the value is contained in the array
10404 */
10405 private static boolean scanArgs(String[] args, String value) {
10406 if (args != null) {
10407 for (String arg : args) {
10408 if (value.equals(arg)) {
10409 return true;
10410 }
10411 }
10412 }
10413 return false;
10414 }
10415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010416 private final void killServicesLocked(ProcessRecord app,
10417 boolean allowRestart) {
10418 // Report disconnected services.
10419 if (false) {
10420 // XXX we are letting the client link to the service for
10421 // death notifications.
10422 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010423 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010425 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010426 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010427 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010428 = r.connections.values().iterator();
10429 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010430 ArrayList<ConnectionRecord> cl = jt.next();
10431 for (int i=0; i<cl.size(); i++) {
10432 ConnectionRecord c = cl.get(i);
10433 if (c.binding.client != app) {
10434 try {
10435 //c.conn.connected(r.className, null);
10436 } catch (Exception e) {
10437 // todo: this should be asynchronous!
10438 Slog.w(TAG, "Exception thrown disconnected servce "
10439 + r.shortName
10440 + " from app " + app.processName, e);
10441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010442 }
10443 }
10444 }
10445 }
10446 }
10447 }
10448 }
10449
10450 // Clean up any connections this application has to other services.
10451 if (app.connections.size() > 0) {
10452 Iterator<ConnectionRecord> it = app.connections.iterator();
10453 while (it.hasNext()) {
10454 ConnectionRecord r = it.next();
10455 removeConnectionLocked(r, app, null);
10456 }
10457 }
10458 app.connections.clear();
10459
10460 if (app.services.size() != 0) {
10461 // Any services running in the application need to be placed
10462 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010463 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010464 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010465 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010466 synchronized (sr.stats.getBatteryStats()) {
10467 sr.stats.stopLaunchedLocked();
10468 }
10469 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010470 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010471 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010472 if (mStoppingServices.remove(sr)) {
10473 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10474 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010475
10476 boolean hasClients = sr.bindings.size() > 0;
10477 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010478 Iterator<IntentBindRecord> bindings
10479 = sr.bindings.values().iterator();
10480 while (bindings.hasNext()) {
10481 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010482 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 + ": shouldUnbind=" + b.hasBound);
10484 b.binder = null;
10485 b.requested = b.received = b.hasBound = false;
10486 }
10487 }
10488
Dianne Hackborn070783f2010-12-29 16:46:28 -080010489 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10490 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010491 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010492 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010493 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 sr.crashCount, sr.shortName, app.pid);
10495 bringDownServiceLocked(sr, true);
10496 } else if (!allowRestart) {
10497 bringDownServiceLocked(sr, true);
10498 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010499 boolean canceled = scheduleServiceRestartLocked(sr, true);
10500
10501 // Should the service remain running? Note that in the
10502 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010503 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010504 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10505 if (sr.pendingStarts.size() == 0) {
10506 sr.startRequested = false;
10507 if (!hasClients) {
10508 // Whoops, no reason to restart!
10509 bringDownServiceLocked(sr, true);
10510 }
10511 }
10512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010513 }
10514 }
10515
10516 if (!allowRestart) {
10517 app.services.clear();
10518 }
10519 }
10520
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010521 // Make sure we have no more records on the stopping list.
10522 int i = mStoppingServices.size();
10523 while (i > 0) {
10524 i--;
10525 ServiceRecord sr = mStoppingServices.get(i);
10526 if (sr.app == app) {
10527 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010528 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010529 }
10530 }
10531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010532 app.executingServices.clear();
10533 }
10534
10535 private final void removeDyingProviderLocked(ProcessRecord proc,
10536 ContentProviderRecord cpr) {
10537 synchronized (cpr) {
10538 cpr.launchingApp = null;
10539 cpr.notifyAll();
10540 }
10541
Amith Yamasani742a6712011-05-04 14:49:28 -070010542 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010543 String names[] = cpr.info.authority.split(";");
10544 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010545 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010546 }
10547
10548 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10549 while (cit.hasNext()) {
10550 ProcessRecord capp = cit.next();
10551 if (!capp.persistent && capp.thread != null
10552 && capp.pid != 0
10553 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010554 Slog.i(TAG, "Kill " + capp.processName
10555 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010556 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010557 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010558 capp.processName, capp.setAdj, "dying provider "
10559 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010560 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 }
10562 }
10563
10564 mLaunchingProviders.remove(cpr);
10565 }
10566
10567 /**
10568 * Main code for cleaning up a process when it has gone away. This is
10569 * called both as a result of the process dying, or directly when stopping
10570 * a process when running in single process mode.
10571 */
10572 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010573 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010575 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 }
10577
Dianne Hackborn36124872009-10-08 16:22:03 -070010578 mProcessesToGc.remove(app);
10579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 // Dismiss any open dialogs.
10581 if (app.crashDialog != null) {
10582 app.crashDialog.dismiss();
10583 app.crashDialog = null;
10584 }
10585 if (app.anrDialog != null) {
10586 app.anrDialog.dismiss();
10587 app.anrDialog = null;
10588 }
10589 if (app.waitDialog != null) {
10590 app.waitDialog.dismiss();
10591 app.waitDialog = null;
10592 }
10593
10594 app.crashing = false;
10595 app.notResponding = false;
10596
10597 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010598 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 app.thread = null;
10600 app.forcingToForeground = null;
10601 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010602 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010603 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010604 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010606 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607
10608 boolean restart = false;
10609
10610 int NL = mLaunchingProviders.size();
10611
10612 // Remove published content providers.
10613 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010614 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010615 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010616 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010617 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010618 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010619
10620 // See if someone is waiting for this provider... in which
10621 // case we don't remove it, but just let it restart.
10622 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010623 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010624 for (; i<NL; i++) {
10625 if (mLaunchingProviders.get(i) == cpr) {
10626 restart = true;
10627 break;
10628 }
10629 }
10630 } else {
10631 i = NL;
10632 }
10633
10634 if (i >= NL) {
10635 removeDyingProviderLocked(app, cpr);
10636 NL = mLaunchingProviders.size();
10637 }
10638 }
10639 app.pubProviders.clear();
10640 }
10641
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010642 // Take care of any launching providers waiting for this process.
10643 if (checkAppInLaunchingProvidersLocked(app, false)) {
10644 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010645 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010647 // Unregister from connected content providers.
10648 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010649 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010650 while (it.hasNext()) {
10651 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10652 cpr.clients.remove(app);
10653 }
10654 app.conProviders.clear();
10655 }
10656
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010657 // At this point there may be remaining entries in mLaunchingProviders
10658 // where we were the only one waiting, so they are no longer of use.
10659 // Look for these and clean up if found.
10660 // XXX Commented out for now. Trying to figure out a way to reproduce
10661 // the actual situation to identify what is actually going on.
10662 if (false) {
10663 for (int i=0; i<NL; i++) {
10664 ContentProviderRecord cpr = (ContentProviderRecord)
10665 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010666 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010667 synchronized (cpr) {
10668 cpr.launchingApp = null;
10669 cpr.notifyAll();
10670 }
10671 }
10672 }
10673 }
10674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 skipCurrentReceiverLocked(app);
10676
10677 // Unregister any receivers.
10678 if (app.receivers.size() > 0) {
10679 Iterator<ReceiverList> it = app.receivers.iterator();
10680 while (it.hasNext()) {
10681 removeReceiverLocked(it.next());
10682 }
10683 app.receivers.clear();
10684 }
10685
Christopher Tate181fafa2009-05-14 11:12:14 -070010686 // If the app is undergoing backup, tell the backup manager about it
10687 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010688 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010689 try {
10690 IBackupManager bm = IBackupManager.Stub.asInterface(
10691 ServiceManager.getService(Context.BACKUP_SERVICE));
10692 bm.agentDisconnected(app.info.packageName);
10693 } catch (RemoteException e) {
10694 // can't happen; backup manager is local
10695 }
10696 }
10697
Jeff Sharkey287bd832011-05-28 19:36:26 -070010698 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 // If the caller is restarting this app, then leave it in its
10701 // current lists and let the caller take care of it.
10702 if (restarting) {
10703 return;
10704 }
10705
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010706 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010707 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010708 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010709 mProcessNames.remove(app.processName, app.uid);
10710 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010711 if (mHeavyWeightProcess == app) {
10712 mHeavyWeightProcess = null;
10713 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010715 } else if (!app.removed) {
10716 // This app is persistent, so we need to keep its record around.
10717 // If it is not already on the pending app list, add it there
10718 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010719 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10720 mPersistentStartingProcesses.add(app);
10721 restart = true;
10722 }
10723 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010724 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10725 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 mProcessesOnHold.remove(app);
10727
The Android Open Source Project4df24232009-03-05 14:34:35 -080010728 if (app == mHomeProcess) {
10729 mHomeProcess = null;
10730 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010731 if (app == mPreviousProcess) {
10732 mPreviousProcess = null;
10733 }
10734
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010735 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 // We have components that still need to be running in the
10737 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010738 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 startProcessLocked(app, "restart", app.processName);
10740 } else if (app.pid > 0 && app.pid != MY_PID) {
10741 // Goodbye!
10742 synchronized (mPidsSelfLocked) {
10743 mPidsSelfLocked.remove(app.pid);
10744 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10745 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010746 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010747 }
10748 }
10749
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010750 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10751 // Look through the content providers we are waiting to have launched,
10752 // and if any run in this process then either schedule a restart of
10753 // the process or kill the client waiting for it if this process has
10754 // gone bad.
10755 int NL = mLaunchingProviders.size();
10756 boolean restart = false;
10757 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010758 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010759 if (cpr.launchingApp == app) {
10760 if (!alwaysBad && !app.bad) {
10761 restart = true;
10762 } else {
10763 removeDyingProviderLocked(app, cpr);
10764 NL = mLaunchingProviders.size();
10765 }
10766 }
10767 }
10768 return restart;
10769 }
10770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 // =========================================================
10772 // SERVICES
10773 // =========================================================
10774
10775 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10776 ActivityManager.RunningServiceInfo info =
10777 new ActivityManager.RunningServiceInfo();
10778 info.service = r.name;
10779 if (r.app != null) {
10780 info.pid = r.app.pid;
10781 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010782 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 info.process = r.processName;
10784 info.foreground = r.isForeground;
10785 info.activeSince = r.createTime;
10786 info.started = r.startRequested;
10787 info.clientCount = r.connections.size();
10788 info.crashCount = r.crashCount;
10789 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010790 if (r.isForeground) {
10791 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10792 }
10793 if (r.startRequested) {
10794 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10795 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010796 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010797 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10798 }
10799 if (r.app != null && r.app.persistent) {
10800 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10801 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010802
10803 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10804 for (int i=0; i<connl.size(); i++) {
10805 ConnectionRecord conn = connl.get(i);
10806 if (conn.clientLabel != 0) {
10807 info.clientPackage = conn.binding.client.info.packageName;
10808 info.clientLabel = conn.clientLabel;
10809 return info;
10810 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010811 }
10812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 return info;
10814 }
10815
10816 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10817 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010818 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 synchronized (this) {
10820 ArrayList<ActivityManager.RunningServiceInfo> res
10821 = new ArrayList<ActivityManager.RunningServiceInfo>();
10822
Amith Yamasani742a6712011-05-04 14:49:28 -070010823 int userId = UserId.getUserId(Binder.getCallingUid());
10824 if (mServiceMap.getAllServices(userId).size() > 0) {
10825 Iterator<ServiceRecord> it
10826 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010827 while (it.hasNext() && res.size() < maxNum) {
10828 res.add(makeRunningServiceInfoLocked(it.next()));
10829 }
10830 }
10831
10832 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10833 ServiceRecord r = mRestartingServices.get(i);
10834 ActivityManager.RunningServiceInfo info =
10835 makeRunningServiceInfoLocked(r);
10836 info.restarting = r.nextRestartTime;
10837 res.add(info);
10838 }
10839
10840 return res;
10841 }
10842 }
10843
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010844 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010845 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010846 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010847 int userId = UserId.getUserId(Binder.getCallingUid());
10848 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010849 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010850 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10851 for (int i=0; i<conn.size(); i++) {
10852 if (conn.get(i).clientIntent != null) {
10853 return conn.get(i).clientIntent;
10854 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010855 }
10856 }
10857 }
10858 }
10859 return null;
10860 }
10861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862 private final ServiceRecord findServiceLocked(ComponentName name,
10863 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010864 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 return r == token ? r : null;
10866 }
10867
10868 private final class ServiceLookupResult {
10869 final ServiceRecord record;
10870 final String permission;
10871
10872 ServiceLookupResult(ServiceRecord _record, String _permission) {
10873 record = _record;
10874 permission = _permission;
10875 }
10876 };
10877
10878 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010879 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 ServiceRecord r = null;
10881 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010882 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 }
10884 if (r == null) {
10885 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010886 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 }
10888
10889 if (r == null) {
10890 try {
10891 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010892 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010893 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 ServiceInfo sInfo =
10895 rInfo != null ? rInfo.serviceInfo : null;
10896 if (sInfo == null) {
10897 return null;
10898 }
10899
10900 ComponentName name = new ComponentName(
10901 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010902 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010903 } catch (RemoteException ex) {
10904 // pm is in same process, this will never happen.
10905 }
10906 }
10907 if (r != null) {
10908 int callingPid = Binder.getCallingPid();
10909 int callingUid = Binder.getCallingUid();
10910 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010911 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010912 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010913 if (!r.exported) {
10914 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10915 + " from pid=" + callingPid
10916 + ", uid=" + callingUid
10917 + " that is not exported from uid " + r.appInfo.uid);
10918 return new ServiceLookupResult(null, "not exported from uid "
10919 + r.appInfo.uid);
10920 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010921 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 + " from pid=" + callingPid
10923 + ", uid=" + callingUid
10924 + " requires " + r.permission);
10925 return new ServiceLookupResult(null, r.permission);
10926 }
10927 return new ServiceLookupResult(r, null);
10928 }
10929 return null;
10930 }
10931
10932 private class ServiceRestarter implements Runnable {
10933 private ServiceRecord mService;
10934
10935 void setService(ServiceRecord service) {
10936 mService = service;
10937 }
10938
10939 public void run() {
10940 synchronized(ActivityManagerService.this) {
10941 performServiceRestartLocked(mService);
10942 }
10943 }
10944 }
10945
10946 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010947 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010949 if (DEBUG_SERVICE)
10950 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010951 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010954 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010955 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010956 if (r == null) {
10957 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010958 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 if (r == null) {
10961 try {
10962 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010963 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010964 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 ServiceInfo sInfo =
10966 rInfo != null ? rInfo.serviceInfo : null;
10967 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010968 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 ": not found");
10970 return null;
10971 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010972 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010973 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10974 userId = 0;
10975 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010976 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010978 ComponentName name = new ComponentName(
10979 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010980 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010982 Intent.FilterComparison filter = new Intent.FilterComparison(
10983 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 ServiceRestarter res = new ServiceRestarter();
10985 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10986 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10987 synchronized (stats) {
10988 ss = stats.getServiceStatsLocked(
10989 sInfo.applicationInfo.uid, sInfo.packageName,
10990 sInfo.name);
10991 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010992 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010993 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010994 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10995 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010996
10997 // Make sure this component isn't in the pending list.
10998 int N = mPendingServices.size();
10999 for (int i=0; i<N; i++) {
11000 ServiceRecord pr = mPendingServices.get(i);
11001 if (pr.name.equals(name)) {
11002 mPendingServices.remove(i);
11003 i--;
11004 N--;
11005 }
11006 }
11007 }
11008 } catch (RemoteException ex) {
11009 // pm is in same process, this will never happen.
11010 }
11011 }
11012 if (r != null) {
11013 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011014 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011016 if (!r.exported) {
11017 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11018 + " from pid=" + callingPid
11019 + ", uid=" + callingUid
11020 + " that is not exported from uid " + r.appInfo.uid);
11021 return new ServiceLookupResult(null, "not exported from uid "
11022 + r.appInfo.uid);
11023 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011024 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011025 + " from pid=" + callingPid
11026 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 + " requires " + r.permission);
11028 return new ServiceLookupResult(null, r.permission);
11029 }
11030 return new ServiceLookupResult(r, null);
11031 }
11032 return null;
11033 }
11034
Dianne Hackborn287952c2010-09-22 22:34:31 -070011035 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11036 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11037 + why + " of " + r + " in app " + r.app);
11038 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11039 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 long now = SystemClock.uptimeMillis();
11041 if (r.executeNesting == 0 && r.app != null) {
11042 if (r.app.executingServices.size() == 0) {
11043 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11044 msg.obj = r.app;
11045 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11046 }
11047 r.app.executingServices.add(r);
11048 }
11049 r.executeNesting++;
11050 r.executingStart = now;
11051 }
11052
11053 private final void sendServiceArgsLocked(ServiceRecord r,
11054 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011055 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011056 if (N == 0) {
11057 return;
11058 }
11059
Dianne Hackborn39792d22010-08-19 18:01:52 -070011060 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011062 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011063 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11064 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011065 if (si.intent == null && N > 1) {
11066 // If somehow we got a dummy null intent in the middle,
11067 // then skip it. DO NOT skip a null intent when it is
11068 // the only one in the list -- this is to support the
11069 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011070 continue;
11071 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011072 si.deliveredTime = SystemClock.uptimeMillis();
11073 r.deliveredStarts.add(si);
11074 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011075 if (si.neededGrants != null) {
11076 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11077 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011078 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011079 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011080 if (!oomAdjusted) {
11081 oomAdjusted = true;
11082 updateOomAdjLocked(r.app);
11083 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011084 int flags = 0;
Dianne Hackbornd8f10242012-05-08 17:14:58 -070011085 if (si.deliveryCount > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011086 flags |= Service.START_FLAG_RETRY;
11087 }
11088 if (si.doneExecutingCount > 0) {
11089 flags |= Service.START_FLAG_REDELIVERY;
11090 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011091 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011092 } catch (RemoteException e) {
11093 // Remote process gone... we'll let the normal cleanup take
11094 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011095 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011096 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011097 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011098 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011099 break;
11100 }
11101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 }
11103
11104 private final boolean requestServiceBindingLocked(ServiceRecord r,
11105 IntentBindRecord i, boolean rebind) {
11106 if (r.app == null || r.app.thread == null) {
11107 // If service is not currently running, can't yet bind.
11108 return false;
11109 }
11110 if ((!i.requested || rebind) && i.apps.size() > 0) {
11111 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011112 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011113 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11114 if (!rebind) {
11115 i.requested = true;
11116 }
11117 i.hasBound = true;
11118 i.doRebind = false;
11119 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011120 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 return false;
11122 }
11123 }
11124 return true;
11125 }
11126
11127 private final void requestServiceBindingsLocked(ServiceRecord r) {
11128 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11129 while (bindings.hasNext()) {
11130 IntentBindRecord i = bindings.next();
11131 if (!requestServiceBindingLocked(r, i, false)) {
11132 break;
11133 }
11134 }
11135 }
11136
11137 private final void realStartServiceLocked(ServiceRecord r,
11138 ProcessRecord app) throws RemoteException {
11139 if (app.thread == null) {
11140 throw new RemoteException();
11141 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011142 if (DEBUG_MU)
11143 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011144 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011146 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147
11148 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011149 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011150 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011151
11152 boolean created = false;
11153 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011154 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011155 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011156 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011157 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011158 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011159 synchronized (r.stats.getBatteryStats()) {
11160 r.stats.startLaunchedLocked();
11161 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011162 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011163 app.thread.scheduleCreateService(r, r.serviceInfo,
11164 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011165 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011166 created = true;
11167 } finally {
11168 if (!created) {
11169 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011170 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 }
11172 }
11173
11174 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011175
11176 // If the service is in the started state, and there are no
11177 // pending arguments, then fake up one so its onStartCommand() will
11178 // be called.
11179 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011180 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011181 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011182 }
11183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 sendServiceArgsLocked(r, true);
11185 }
11186
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011187 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11188 boolean allowCancel) {
11189 boolean canceled = false;
11190
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011191 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011192 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011193 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011194
Dianne Hackborn070783f2010-12-29 16:46:28 -080011195 if ((r.serviceInfo.applicationInfo.flags
11196 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11197 minDuration /= 4;
11198 }
11199
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011200 // Any delivered but not yet finished starts should be put back
11201 // on the pending list.
11202 final int N = r.deliveredStarts.size();
11203 if (N > 0) {
11204 for (int i=N-1; i>=0; i--) {
11205 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011206 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011207 if (si.intent == null) {
11208 // We'll generate this again if needed.
11209 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11210 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11211 r.pendingStarts.add(0, si);
11212 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11213 dur *= 2;
11214 if (minDuration < dur) minDuration = dur;
11215 if (resetTime < dur) resetTime = dur;
11216 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011217 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011218 + r.name);
11219 canceled = true;
11220 }
11221 }
11222 r.deliveredStarts.clear();
11223 }
11224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 r.totalRestartCount++;
11226 if (r.restartDelay == 0) {
11227 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011228 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011229 } else {
11230 // If it has been a "reasonably long time" since the service
11231 // was started, then reset our restart duration back to
11232 // the beginning, so we don't infinitely increase the duration
11233 // on a service that just occasionally gets killed (which is
11234 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011235 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011237 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011238 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011239 if ((r.serviceInfo.applicationInfo.flags
11240 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11241 // Services in peristent processes will restart much more
11242 // quickly, since they are pretty important. (Think SystemUI).
11243 r.restartDelay += minDuration/2;
11244 } else {
11245 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11246 if (r.restartDelay < minDuration) {
11247 r.restartDelay = minDuration;
11248 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 }
11251 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011252
11253 r.nextRestartTime = now + r.restartDelay;
11254
11255 // Make sure that we don't end up restarting a bunch of services
11256 // all at the same time.
11257 boolean repeat;
11258 do {
11259 repeat = false;
11260 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11261 ServiceRecord r2 = mRestartingServices.get(i);
11262 if (r2 != r && r.nextRestartTime
11263 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11264 && r.nextRestartTime
11265 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11266 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11267 r.restartDelay = r.nextRestartTime - now;
11268 repeat = true;
11269 break;
11270 }
11271 }
11272 } while (repeat);
11273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 if (!mRestartingServices.contains(r)) {
11275 mRestartingServices.add(r);
11276 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011277
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011278 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011281 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011283 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011284 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011285 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011286 r.shortName, r.restartDelay);
11287
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011288 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011289 }
11290
11291 final void performServiceRestartLocked(ServiceRecord r) {
11292 if (!mRestartingServices.contains(r)) {
11293 return;
11294 }
11295 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11296 }
11297
11298 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11299 if (r.restartDelay == 0) {
11300 return false;
11301 }
11302 r.resetRestartCounter();
11303 mRestartingServices.remove(r);
11304 mHandler.removeCallbacks(r.restarter);
11305 return true;
11306 }
11307
11308 private final boolean bringUpServiceLocked(ServiceRecord r,
11309 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011310 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 //r.dump(" ");
11312
Dianne Hackborn36124872009-10-08 16:22:03 -070011313 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 sendServiceArgsLocked(r, false);
11315 return true;
11316 }
11317
11318 if (!whileRestarting && r.restartDelay > 0) {
11319 // If waiting for a restart, then do nothing.
11320 return true;
11321 }
11322
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011323 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011325 // We are now bringing the service up, so no longer in the
11326 // restarting state.
11327 mRestartingServices.remove(r);
11328
Dianne Hackborne7f97212011-02-24 14:40:20 -080011329 // Service is now being launched, its package can't be stopped.
11330 try {
11331 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011332 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011333 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011334 } catch (IllegalArgumentException e) {
11335 Slog.w(TAG, "Failed trying to unstop package "
11336 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011337 }
11338
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011339 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011340 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011341 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011343 if (!isolated) {
11344 app = getProcessRecordLocked(appName, r.appInfo.uid);
11345 if (DEBUG_MU)
11346 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11347 if (app != null && app.thread != null) {
11348 try {
11349 app.addPackage(r.appInfo.packageName);
11350 realStartServiceLocked(r, app);
11351 return true;
11352 } catch (RemoteException e) {
11353 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11354 }
11355
11356 // If a dead object exception was thrown -- fall through to
11357 // restart the application.
11358 }
11359 } else {
11360 // If this service runs in an isolated process, then each time
11361 // we call startProcessLocked() we will get a new isolated
11362 // process, starting another process if we are currently waiting
11363 // for a previous process to come up. To deal with this, we store
11364 // in the service any current isolated process it is running in or
11365 // waiting to have come up.
11366 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 }
11368
Dianne Hackborn36124872009-10-08 16:22:03 -070011369 // Not running -- get it started, and enqueue this service record
11370 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011371 if (app == null) {
11372 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11373 "service", r.name, false, isolated)) == null) {
11374 Slog.w(TAG, "Unable to launch app "
11375 + r.appInfo.packageName + "/"
11376 + r.appInfo.uid + " for service "
11377 + r.intent.getIntent() + ": process is bad");
11378 bringDownServiceLocked(r, true);
11379 return false;
11380 }
11381 if (isolated) {
11382 r.isolatedProc = app;
11383 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011384 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 mPendingServices.add(r);
11388 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 return true;
11391 }
11392
11393 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011394 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 //r.dump(" ");
11396
11397 // Does it still need to run?
11398 if (!force && r.startRequested) {
11399 return;
11400 }
11401 if (r.connections.size() > 0) {
11402 if (!force) {
11403 // XXX should probably keep a count of the number of auto-create
11404 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011405 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011406 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011407 ArrayList<ConnectionRecord> cr = it.next();
11408 for (int i=0; i<cr.size(); i++) {
11409 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11410 return;
11411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 }
11413 }
11414 }
11415
11416 // Report to all of the connections that the service is no longer
11417 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011418 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011420 ArrayList<ConnectionRecord> c = it.next();
11421 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011422 ConnectionRecord cr = c.get(i);
11423 // There is still a connection to the service that is
11424 // being brought down. Mark it as dead.
11425 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011426 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011427 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011428 } catch (Exception e) {
11429 Slog.w(TAG, "Failure disconnecting service " + r.name +
11430 " to connection " + c.get(i).conn.asBinder() +
11431 " (in " + c.get(i).binding.client.processName + ")", e);
11432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011433 }
11434 }
11435 }
11436
11437 // Tell the service that it has been unbound.
11438 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11439 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11440 while (it.hasNext()) {
11441 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011442 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011443 + ": hasBound=" + ibr.hasBound);
11444 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11445 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011446 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 updateOomAdjLocked(r.app);
11448 ibr.hasBound = false;
11449 r.app.thread.scheduleUnbindService(r,
11450 ibr.intent.getIntent());
11451 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011452 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 + r.shortName, e);
11454 serviceDoneExecutingLocked(r, true);
11455 }
11456 }
11457 }
11458 }
11459
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011460 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011461 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011462 System.identityHashCode(r), r.shortName,
11463 (r.app != null) ? r.app.pid : -1);
11464
Amith Yamasani742a6712011-05-04 14:49:28 -070011465 mServiceMap.removeServiceByName(r.name, r.userId);
11466 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467 r.totalRestartCount = 0;
11468 unscheduleServiceRestartLocked(r);
11469
11470 // Also make sure it is not on the pending list.
11471 int N = mPendingServices.size();
11472 for (int i=0; i<N; i++) {
11473 if (mPendingServices.get(i) == r) {
11474 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011475 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476 i--;
11477 N--;
11478 }
11479 }
11480
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011481 r.cancelNotification();
11482 r.isForeground = false;
11483 r.foregroundId = 0;
11484 r.foregroundNoti = null;
11485
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011486 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011487 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011488 r.pendingStarts.clear();
11489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 if (r.app != null) {
11491 synchronized (r.stats.getBatteryStats()) {
11492 r.stats.stopLaunchedLocked();
11493 }
11494 r.app.services.remove(r);
11495 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011497 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011498 mStoppingServices.add(r);
11499 updateOomAdjLocked(r.app);
11500 r.app.thread.scheduleStopService(r);
11501 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011502 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011503 + r.shortName, e);
11504 serviceDoneExecutingLocked(r, true);
11505 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011506 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011508 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011509 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011510 }
11511 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011512 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011513 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011514 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011515
11516 if (r.bindings.size() > 0) {
11517 r.bindings.clear();
11518 }
11519
11520 if (r.restarter instanceof ServiceRestarter) {
11521 ((ServiceRestarter)r.restarter).setService(null);
11522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011523 }
11524
11525 ComponentName startServiceLocked(IApplicationThread caller,
11526 Intent service, String resolvedType,
11527 int callingPid, int callingUid) {
11528 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011529 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 + " type=" + resolvedType + " args=" + service.getExtras());
11531
11532 if (caller != null) {
11533 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11534 if (callerApp == null) {
11535 throw new SecurityException(
11536 "Unable to find app for caller " + caller
11537 + " (pid=" + Binder.getCallingPid()
11538 + ") when starting service " + service);
11539 }
11540 }
11541
11542 ServiceLookupResult res =
11543 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011544 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011545 if (res == null) {
11546 return null;
11547 }
11548 if (res.record == null) {
11549 return new ComponentName("!", res.permission != null
11550 ? res.permission : "private to package");
11551 }
11552 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011553 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11554 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011556 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 }
11558 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011559 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011560 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011561 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 r.lastActivity = SystemClock.uptimeMillis();
11563 synchronized (r.stats.getBatteryStats()) {
11564 r.stats.startRunningLocked();
11565 }
11566 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11567 return new ComponentName("!", "Service process is bad");
11568 }
11569 return r.name;
11570 }
11571 }
11572
11573 public ComponentName startService(IApplicationThread caller, Intent service,
11574 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011575 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 // Refuse possible leaked file descriptors
11577 if (service != null && service.hasFileDescriptors() == true) {
11578 throw new IllegalArgumentException("File descriptors passed in Intent");
11579 }
11580
Amith Yamasani742a6712011-05-04 14:49:28 -070011581 if (DEBUG_SERVICE)
11582 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583 synchronized(this) {
11584 final int callingPid = Binder.getCallingPid();
11585 final int callingUid = Binder.getCallingUid();
11586 final long origId = Binder.clearCallingIdentity();
11587 ComponentName res = startServiceLocked(caller, service,
11588 resolvedType, callingPid, callingUid);
11589 Binder.restoreCallingIdentity(origId);
11590 return res;
11591 }
11592 }
11593
11594 ComponentName startServiceInPackage(int uid,
11595 Intent service, String resolvedType) {
11596 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011597 if (DEBUG_SERVICE)
11598 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011599 final long origId = Binder.clearCallingIdentity();
11600 ComponentName res = startServiceLocked(null, service,
11601 resolvedType, -1, uid);
11602 Binder.restoreCallingIdentity(origId);
11603 return res;
11604 }
11605 }
11606
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011607 private void stopServiceLocked(ServiceRecord service) {
11608 synchronized (service.stats.getBatteryStats()) {
11609 service.stats.stopRunningLocked();
11610 }
11611 service.startRequested = false;
11612 service.callStart = false;
11613 bringDownServiceLocked(service, false);
11614 }
11615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011616 public int stopService(IApplicationThread caller, Intent service,
11617 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011618 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 // Refuse possible leaked file descriptors
11620 if (service != null && service.hasFileDescriptors() == true) {
11621 throw new IllegalArgumentException("File descriptors passed in Intent");
11622 }
11623
11624 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011625 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626 + " type=" + resolvedType);
11627
11628 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11629 if (caller != null && callerApp == null) {
11630 throw new SecurityException(
11631 "Unable to find app for caller " + caller
11632 + " (pid=" + Binder.getCallingPid()
11633 + ") when stopping service " + service);
11634 }
11635
11636 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011637 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11638 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011639 if (r != null) {
11640 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011642 try {
11643 stopServiceLocked(r.record);
11644 } finally {
11645 Binder.restoreCallingIdentity(origId);
11646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647 return 1;
11648 }
11649 return -1;
11650 }
11651 }
11652
11653 return 0;
11654 }
11655
11656 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011657 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011658 // Refuse possible leaked file descriptors
11659 if (service != null && service.hasFileDescriptors() == true) {
11660 throw new IllegalArgumentException("File descriptors passed in Intent");
11661 }
11662
11663 IBinder ret = null;
11664
11665 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011666 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11667 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011668
11669 if (r != null) {
11670 // r.record is null if findServiceLocked() failed the caller permission check
11671 if (r.record == null) {
11672 throw new SecurityException(
11673 "Permission Denial: Accessing service " + r.record.name
11674 + " from pid=" + Binder.getCallingPid()
11675 + ", uid=" + Binder.getCallingUid()
11676 + " requires " + r.permission);
11677 }
11678 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11679 if (ib != null) {
11680 ret = ib.binder;
11681 }
11682 }
11683 }
11684
11685 return ret;
11686 }
11687
11688 public boolean stopServiceToken(ComponentName className, IBinder token,
11689 int startId) {
11690 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011691 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011692 + " " + token + " startId=" + startId);
11693 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011694 if (r != null) {
11695 if (startId >= 0) {
11696 // Asked to only stop if done with all work. Note that
11697 // to avoid leaks, we will take this as dropping all
11698 // start items up to and including this one.
11699 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11700 if (si != null) {
11701 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011702 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11703 cur.removeUriPermissionsLocked();
11704 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011705 break;
11706 }
11707 }
11708 }
11709
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011710 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011711 return false;
11712 }
11713
11714 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011715 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011716 + " is last, but have " + r.deliveredStarts.size()
11717 + " remaining args");
11718 }
11719 }
11720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 synchronized (r.stats.getBatteryStats()) {
11722 r.stats.stopRunningLocked();
11723 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011724 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011725 }
11726 final long origId = Binder.clearCallingIdentity();
11727 bringDownServiceLocked(r, false);
11728 Binder.restoreCallingIdentity(origId);
11729 return true;
11730 }
11731 }
11732 return false;
11733 }
11734
11735 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011736 int id, Notification notification, boolean removeNotification) {
11737 final long origId = Binder.clearCallingIdentity();
11738 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739 synchronized(this) {
11740 ServiceRecord r = findServiceLocked(className, token);
11741 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011742 if (id != 0) {
11743 if (notification == null) {
11744 throw new IllegalArgumentException("null notification");
11745 }
11746 if (r.foregroundId != id) {
11747 r.cancelNotification();
11748 r.foregroundId = id;
11749 }
11750 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11751 r.foregroundNoti = notification;
11752 r.isForeground = true;
11753 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011754 if (r.app != null) {
11755 updateServiceForegroundLocked(r.app, true);
11756 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011757 } else {
11758 if (r.isForeground) {
11759 r.isForeground = false;
11760 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011761 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011762 updateServiceForegroundLocked(r.app, true);
11763 }
11764 }
11765 if (removeNotification) {
11766 r.cancelNotification();
11767 r.foregroundId = 0;
11768 r.foregroundNoti = null;
11769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 }
11771 }
11772 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011773 } finally {
11774 Binder.restoreCallingIdentity(origId);
11775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 }
11777
11778 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11779 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011780 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011781 if (sr.isForeground) {
11782 anyForeground = true;
11783 break;
11784 }
11785 }
11786 if (anyForeground != proc.foregroundServices) {
11787 proc.foregroundServices = anyForeground;
11788 if (oomAdj) {
11789 updateOomAdjLocked();
11790 }
11791 }
11792 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011793
11794 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11795 boolean result = false;
11796 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11797 result = false;
11798 } else if (componentProcessName == aInfo.packageName) {
11799 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11800 } else if ("system".equals(componentProcessName)) {
11801 result = true;
11802 }
11803 if (DEBUG_MU) {
11804 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11805 }
11806 return result;
11807 }
11808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 public int bindService(IApplicationThread caller, IBinder token,
11810 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011811 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011812 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011813 // Refuse possible leaked file descriptors
11814 if (service != null && service.hasFileDescriptors() == true) {
11815 throw new IllegalArgumentException("File descriptors passed in Intent");
11816 }
11817
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011818 checkValidCaller(Binder.getCallingUid(), userId);
11819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011821 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 + " type=" + resolvedType + " conn=" + connection.asBinder()
11823 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011824 if (DEBUG_MU)
11825 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11826 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11828 if (callerApp == null) {
11829 throw new SecurityException(
11830 "Unable to find app for caller " + caller
11831 + " (pid=" + Binder.getCallingPid()
11832 + ") when binding service " + service);
11833 }
11834
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011835 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011837 activity = mMainStack.isInStackLocked(token);
11838 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011839 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011840 return 0;
11841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842 }
11843
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011844 int clientLabel = 0;
11845 PendingIntent clientIntent = null;
11846
11847 if (callerApp.info.uid == Process.SYSTEM_UID) {
11848 // Hacky kind of thing -- allow system stuff to tell us
11849 // what they are, so we can report this elsewhere for
11850 // others to know why certain services are running.
11851 try {
11852 clientIntent = (PendingIntent)service.getParcelableExtra(
11853 Intent.EXTRA_CLIENT_INTENT);
11854 } catch (RuntimeException e) {
11855 }
11856 if (clientIntent != null) {
11857 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11858 if (clientLabel != 0) {
11859 // There are no useful extras in the intent, trash them.
11860 // System code calling with this stuff just needs to know
11861 // this will happen.
11862 service = service.cloneFilter();
11863 }
11864 }
11865 }
11866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011867 ServiceLookupResult res =
11868 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011869 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011870 if (res == null) {
11871 return 0;
11872 }
11873 if (res.record == null) {
11874 return -1;
11875 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011876 if (isSingleton(res.record.processName, res.record.appInfo)) {
11877 userId = 0;
11878 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11879 Binder.getCallingUid(), 0);
11880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881 ServiceRecord s = res.record;
11882
11883 final long origId = Binder.clearCallingIdentity();
11884
11885 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011886 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011887 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 }
11889
11890 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11891 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011892 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011893
11894 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011895 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11896 if (clist == null) {
11897 clist = new ArrayList<ConnectionRecord>();
11898 s.connections.put(binder, clist);
11899 }
11900 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011901 b.connections.add(c);
11902 if (activity != null) {
11903 if (activity.connections == null) {
11904 activity.connections = new HashSet<ConnectionRecord>();
11905 }
11906 activity.connections.add(c);
11907 }
11908 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011909 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11910 b.client.hasAboveClient = true;
11911 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011912 clist = mServiceConnections.get(binder);
11913 if (clist == null) {
11914 clist = new ArrayList<ConnectionRecord>();
11915 mServiceConnections.put(binder, clist);
11916 }
11917 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011918
11919 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11920 s.lastActivity = SystemClock.uptimeMillis();
11921 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11922 return 0;
11923 }
11924 }
11925
11926 if (s.app != null) {
11927 // This could have made the service more important.
11928 updateOomAdjLocked(s.app);
11929 }
11930
Joe Onorato8a9b2202010-02-26 18:56:32 -080011931 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011932 + ": received=" + b.intent.received
11933 + " apps=" + b.intent.apps.size()
11934 + " doRebind=" + b.intent.doRebind);
11935
11936 if (s.app != null && b.intent.received) {
11937 // Service is already running, so we can immediately
11938 // publish the connection.
11939 try {
11940 c.conn.connected(s.name, b.intent.binder);
11941 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011942 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943 + " to connection " + c.conn.asBinder()
11944 + " (in " + c.binding.client.processName + ")", e);
11945 }
11946
11947 // If this is the first app connected back to this binding,
11948 // and the service had previously asked to be told when
11949 // rebound, then do so.
11950 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11951 requestServiceBindingLocked(s, b.intent, true);
11952 }
11953 } else if (!b.intent.requested) {
11954 requestServiceBindingLocked(s, b.intent, false);
11955 }
11956
11957 Binder.restoreCallingIdentity(origId);
11958 }
11959
11960 return 1;
11961 }
11962
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011963 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011964 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011965 IBinder binder = c.conn.asBinder();
11966 AppBindRecord b = c.binding;
11967 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011968 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11969 if (clist != null) {
11970 clist.remove(c);
11971 if (clist.size() == 0) {
11972 s.connections.remove(binder);
11973 }
11974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 b.connections.remove(c);
11976 if (c.activity != null && c.activity != skipAct) {
11977 if (c.activity.connections != null) {
11978 c.activity.connections.remove(c);
11979 }
11980 }
11981 if (b.client != skipApp) {
11982 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011983 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11984 b.client.updateHasAboveClientLocked();
11985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011986 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011987 clist = mServiceConnections.get(binder);
11988 if (clist != null) {
11989 clist.remove(c);
11990 if (clist.size() == 0) {
11991 mServiceConnections.remove(binder);
11992 }
11993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011994
11995 if (b.connections.size() == 0) {
11996 b.intent.apps.remove(b.client);
11997 }
11998
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011999 if (!c.serviceDead) {
12000 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12001 + ": shouldUnbind=" + b.intent.hasBound);
12002 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12003 && b.intent.hasBound) {
12004 try {
12005 bumpServiceExecutingLocked(s, "unbind");
12006 updateOomAdjLocked(s.app);
12007 b.intent.hasBound = false;
12008 // Assume the client doesn't want to know about a rebind;
12009 // we will deal with that later if it asks for one.
12010 b.intent.doRebind = false;
12011 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12012 } catch (Exception e) {
12013 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12014 serviceDoneExecutingLocked(s, true);
12015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012017
12018 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12019 bringDownServiceLocked(s, false);
12020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 }
12022 }
12023
12024 public boolean unbindService(IServiceConnection connection) {
12025 synchronized (this) {
12026 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012027 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012028 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12029 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012030 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012031 + connection.asBinder());
12032 return false;
12033 }
12034
12035 final long origId = Binder.clearCallingIdentity();
12036
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012037 while (clist.size() > 0) {
12038 ConnectionRecord r = clist.get(0);
12039 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012040
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012041 if (r.binding.service.app != null) {
12042 // This could have made the service less important.
12043 updateOomAdjLocked(r.binding.service.app);
12044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012045 }
12046
12047 Binder.restoreCallingIdentity(origId);
12048 }
12049
12050 return true;
12051 }
12052
12053 public void publishService(IBinder token, Intent intent, IBinder service) {
12054 // Refuse possible leaked file descriptors
12055 if (intent != null && intent.hasFileDescriptors() == true) {
12056 throw new IllegalArgumentException("File descriptors passed in Intent");
12057 }
12058
12059 synchronized(this) {
12060 if (!(token instanceof ServiceRecord)) {
12061 throw new IllegalArgumentException("Invalid service token");
12062 }
12063 ServiceRecord r = (ServiceRecord)token;
12064
12065 final long origId = Binder.clearCallingIdentity();
12066
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012067 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012068 + " " + intent + ": " + service);
12069 if (r != null) {
12070 Intent.FilterComparison filter
12071 = new Intent.FilterComparison(intent);
12072 IntentBindRecord b = r.bindings.get(filter);
12073 if (b != null && !b.received) {
12074 b.binder = service;
12075 b.requested = true;
12076 b.received = true;
12077 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012078 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012079 = r.connections.values().iterator();
12080 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012081 ArrayList<ConnectionRecord> clist = it.next();
12082 for (int i=0; i<clist.size(); i++) {
12083 ConnectionRecord c = clist.get(i);
12084 if (!filter.equals(c.binding.intent.intent)) {
12085 if (DEBUG_SERVICE) Slog.v(
12086 TAG, "Not publishing to: " + c);
12087 if (DEBUG_SERVICE) Slog.v(
12088 TAG, "Bound intent: " + c.binding.intent.intent);
12089 if (DEBUG_SERVICE) Slog.v(
12090 TAG, "Published intent: " + intent);
12091 continue;
12092 }
12093 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12094 try {
12095 c.conn.connected(r.name, service);
12096 } catch (Exception e) {
12097 Slog.w(TAG, "Failure sending service " + r.name +
12098 " to connection " + c.conn.asBinder() +
12099 " (in " + c.binding.client.processName + ")", e);
12100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 }
12102 }
12103 }
12104 }
12105
12106 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12107
12108 Binder.restoreCallingIdentity(origId);
12109 }
12110 }
12111 }
12112
12113 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12114 // Refuse possible leaked file descriptors
12115 if (intent != null && intent.hasFileDescriptors() == true) {
12116 throw new IllegalArgumentException("File descriptors passed in Intent");
12117 }
12118
12119 synchronized(this) {
12120 if (!(token instanceof ServiceRecord)) {
12121 throw new IllegalArgumentException("Invalid service token");
12122 }
12123 ServiceRecord r = (ServiceRecord)token;
12124
12125 final long origId = Binder.clearCallingIdentity();
12126
12127 if (r != null) {
12128 Intent.FilterComparison filter
12129 = new Intent.FilterComparison(intent);
12130 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012131 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 + " at " + b + ": apps="
12133 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012134
12135 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012136 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012137 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 // Applications have already bound since the last
12139 // unbind, so just rebind right here.
12140 requestServiceBindingLocked(r, b, true);
12141 } else {
12142 // Note to tell the service the next time there is
12143 // a new client.
12144 b.doRebind = true;
12145 }
12146 }
12147
Per Edelberg78f9fff2010-08-30 20:01:35 +020012148 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012149
12150 Binder.restoreCallingIdentity(origId);
12151 }
12152 }
12153 }
12154
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012155 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012156 synchronized(this) {
12157 if (!(token instanceof ServiceRecord)) {
12158 throw new IllegalArgumentException("Invalid service token");
12159 }
12160 ServiceRecord r = (ServiceRecord)token;
12161 boolean inStopping = mStoppingServices.contains(token);
12162 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012163 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012164 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012165 + " with incorrect token: given " + token
12166 + ", expected " + r);
12167 return;
12168 }
12169
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012170 if (type == 1) {
12171 // This is a call from a service start... take care of
12172 // book-keeping.
12173 r.callStart = true;
12174 switch (res) {
12175 case Service.START_STICKY_COMPATIBILITY:
12176 case Service.START_STICKY: {
12177 // We are done with the associated start arguments.
12178 r.findDeliveredStart(startId, true);
12179 // Don't stop if killed.
12180 r.stopIfKilled = false;
12181 break;
12182 }
12183 case Service.START_NOT_STICKY: {
12184 // We are done with the associated start arguments.
12185 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012186 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012187 // There is no more work, and this service
12188 // doesn't want to hang around if killed.
12189 r.stopIfKilled = true;
12190 }
12191 break;
12192 }
12193 case Service.START_REDELIVER_INTENT: {
12194 // We'll keep this item until they explicitly
12195 // call stop for it, but keep track of the fact
12196 // that it was delivered.
12197 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12198 if (si != null) {
12199 si.deliveryCount = 0;
12200 si.doneExecutingCount++;
12201 // Don't stop if killed.
12202 r.stopIfKilled = true;
12203 }
12204 break;
12205 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012206 case Service.START_TASK_REMOVED_COMPLETE: {
12207 // Special processing for onTaskRemoved(). Don't
12208 // impact normal onStartCommand() processing.
12209 r.findDeliveredStart(startId, true);
12210 break;
12211 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012212 default:
12213 throw new IllegalArgumentException(
12214 "Unknown service start result: " + res);
12215 }
12216 if (res == Service.START_STICKY_COMPATIBILITY) {
12217 r.callStart = false;
12218 }
12219 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012220 if (DEBUG_MU)
12221 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12222 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 final long origId = Binder.clearCallingIdentity();
12224 serviceDoneExecutingLocked(r, inStopping);
12225 Binder.restoreCallingIdentity(origId);
12226 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012227 Slog.w(TAG, "Done executing unknown service from pid "
12228 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 }
12230 }
12231 }
12232
12233 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012234 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12235 + ": nesting=" + r.executeNesting
12236 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012237 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012238 r.executeNesting--;
12239 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012240 if (DEBUG_SERVICE) Slog.v(TAG,
12241 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012242 r.app.executingServices.remove(r);
12243 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012244 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12245 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012246 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12247 }
12248 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012249 if (DEBUG_SERVICE) Slog.v(TAG,
12250 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012252 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
12254 updateOomAdjLocked(r.app);
12255 }
12256 }
12257
12258 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012259 String anrMessage = null;
12260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012261 synchronized(this) {
12262 if (proc.executingServices.size() == 0 || proc.thread == null) {
12263 return;
12264 }
12265 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12266 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12267 ServiceRecord timeout = null;
12268 long nextTime = 0;
12269 while (it.hasNext()) {
12270 ServiceRecord sr = it.next();
12271 if (sr.executingStart < maxTime) {
12272 timeout = sr;
12273 break;
12274 }
12275 if (sr.executingStart > nextTime) {
12276 nextTime = sr.executingStart;
12277 }
12278 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012279 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012280 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012281 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012282 } else {
12283 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12284 msg.obj = proc;
12285 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12286 }
12287 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012288
12289 if (anrMessage != null) {
12290 appNotResponding(proc, null, null, anrMessage);
12291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012292 }
12293
12294 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012295 // BACKUP AND RESTORE
12296 // =========================================================
12297
12298 // Cause the target app to be launched if necessary and its backup agent
12299 // instantiated. The backup agent will invoke backupAgentCreated() on the
12300 // activity manager to announce its creation.
12301 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012302 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012303 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12304
12305 synchronized(this) {
12306 // !!! TODO: currently no check here that we're already bound
12307 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12308 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12309 synchronized (stats) {
12310 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12311 }
12312
Dianne Hackborne7f97212011-02-24 14:40:20 -080012313 // Backup agent is now in use, its package can't be stopped.
12314 try {
12315 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012316 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012317 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012318 } catch (IllegalArgumentException e) {
12319 Slog.w(TAG, "Failed trying to unstop package "
12320 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012321 }
12322
Christopher Tate181fafa2009-05-14 11:12:14 -070012323 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012324 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12325 ? new ComponentName(app.packageName, app.backupAgentName)
12326 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012327 // startProcessLocked() returns existing proc's record if it's already running
12328 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012329 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012330 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012331 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012332 return false;
12333 }
12334
12335 r.app = proc;
12336 mBackupTarget = r;
12337 mBackupAppName = app.packageName;
12338
Christopher Tate6fa95972009-06-05 18:43:55 -070012339 // Try not to kill the process during backup
12340 updateOomAdjLocked(proc);
12341
Christopher Tate181fafa2009-05-14 11:12:14 -070012342 // If the process is already attached, schedule the creation of the backup agent now.
12343 // If it is not yet live, this will be done when it attaches to the framework.
12344 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012345 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012346 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012347 proc.thread.scheduleCreateBackupAgent(app,
12348 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012349 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012350 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012351 }
12352 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012353 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012354 }
12355 // Invariants: at this point, the target app process exists and the application
12356 // is either already running or in the process of coming up. mBackupTarget and
12357 // mBackupAppName describe the app, so that when it binds back to the AM we
12358 // know that it's scheduled for a backup-agent operation.
12359 }
12360
12361 return true;
12362 }
12363
12364 // A backup agent has just come up
12365 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012366 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012367 + " = " + agent);
12368
12369 synchronized(this) {
12370 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012371 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012372 return;
12373 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012374 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012375
Dianne Hackborn06740692010-09-22 22:46:21 -070012376 long oldIdent = Binder.clearCallingIdentity();
12377 try {
12378 IBackupManager bm = IBackupManager.Stub.asInterface(
12379 ServiceManager.getService(Context.BACKUP_SERVICE));
12380 bm.agentConnected(agentPackageName, agent);
12381 } catch (RemoteException e) {
12382 // can't happen; the backup manager service is local
12383 } catch (Exception e) {
12384 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12385 e.printStackTrace();
12386 } finally {
12387 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012388 }
12389 }
12390
12391 // done with this agent
12392 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012393 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012394 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012395 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012396 return;
12397 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012398
12399 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012400 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012401 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012402 return;
12403 }
12404
Christopher Tate181fafa2009-05-14 11:12:14 -070012405 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012406 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012407 return;
12408 }
12409
Christopher Tate6fa95972009-06-05 18:43:55 -070012410 ProcessRecord proc = mBackupTarget.app;
12411 mBackupTarget = null;
12412 mBackupAppName = null;
12413
12414 // Not backing this app up any more; reset its OOM adjustment
12415 updateOomAdjLocked(proc);
12416
Christopher Tatec7b31e32009-06-10 15:49:30 -070012417 // If the app crashed during backup, 'thread' will be null here
12418 if (proc.thread != null) {
12419 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012420 proc.thread.scheduleDestroyBackupAgent(appInfo,
12421 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012422 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012423 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012424 e.printStackTrace();
12425 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012426 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012427 }
12428 }
12429 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012430 // BROADCASTS
12431 // =========================================================
12432
Josh Bartel7f208742010-02-25 11:01:44 -060012433 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434 List cur) {
12435 final ContentResolver resolver = mContext.getContentResolver();
12436 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12437 if (list == null) {
12438 return cur;
12439 }
12440 int N = list.size();
12441 for (int i=0; i<N; i++) {
12442 Intent intent = list.get(i);
12443 if (filter.match(resolver, intent, true, TAG) >= 0) {
12444 if (cur == null) {
12445 cur = new ArrayList<Intent>();
12446 }
12447 cur.add(intent);
12448 }
12449 }
12450 return cur;
12451 }
12452
Christopher Tatef46723b2012-01-26 14:19:24 -080012453 boolean isPendingBroadcastProcessLocked(int pid) {
12454 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12455 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012457
Christopher Tatef46723b2012-01-26 14:19:24 -080012458 void skipPendingBroadcastLocked(int pid) {
12459 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12460 for (BroadcastQueue queue : mBroadcastQueues) {
12461 queue.skipPendingBroadcastLocked(pid);
12462 }
12463 }
12464
12465 // The app just attached; send any pending broadcasts that it should receive
12466 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12467 boolean didSomething = false;
12468 for (BroadcastQueue queue : mBroadcastQueues) {
12469 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012471 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012472 }
12473
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012474 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012476 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 synchronized(this) {
12478 ProcessRecord callerApp = null;
12479 if (caller != null) {
12480 callerApp = getRecordForAppLocked(caller);
12481 if (callerApp == null) {
12482 throw new SecurityException(
12483 "Unable to find app for caller " + caller
12484 + " (pid=" + Binder.getCallingPid()
12485 + ") when registering receiver " + receiver);
12486 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012487 if (callerApp.info.uid != Process.SYSTEM_UID &&
12488 !callerApp.pkgList.contains(callerPackage)) {
12489 throw new SecurityException("Given caller package " + callerPackage
12490 + " is not running in process " + callerApp);
12491 }
12492 } else {
12493 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012494 }
12495
12496 List allSticky = null;
12497
12498 // Look for any matching sticky broadcasts...
12499 Iterator actions = filter.actionsIterator();
12500 if (actions != null) {
12501 while (actions.hasNext()) {
12502 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012503 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012504 }
12505 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012506 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012507 }
12508
12509 // The first sticky in the list is returned directly back to
12510 // the client.
12511 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12512
Joe Onorato8a9b2202010-02-26 18:56:32 -080012513 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012514 + ": " + sticky);
12515
12516 if (receiver == null) {
12517 return sticky;
12518 }
12519
12520 ReceiverList rl
12521 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12522 if (rl == null) {
12523 rl = new ReceiverList(this, callerApp,
12524 Binder.getCallingPid(),
12525 Binder.getCallingUid(), receiver);
12526 if (rl.app != null) {
12527 rl.app.receivers.add(rl);
12528 } else {
12529 try {
12530 receiver.asBinder().linkToDeath(rl, 0);
12531 } catch (RemoteException e) {
12532 return sticky;
12533 }
12534 rl.linkedToDeath = true;
12535 }
12536 mRegisteredReceivers.put(receiver.asBinder(), rl);
12537 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012538 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539 rl.add(bf);
12540 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012541 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012542 }
12543 mReceiverResolver.addFilter(bf);
12544
12545 // Enqueue broadcasts for all existing stickies that match
12546 // this filter.
12547 if (allSticky != null) {
12548 ArrayList receivers = new ArrayList();
12549 receivers.add(bf);
12550
12551 int N = allSticky.size();
12552 for (int i=0; i<N; i++) {
12553 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012554 BroadcastQueue queue = broadcastQueueForIntent(intent);
12555 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012557 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012558 queue.enqueueParallelBroadcastLocked(r);
12559 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012560 }
12561 }
12562
12563 return sticky;
12564 }
12565 }
12566
12567 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012568 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012569
Christopher Tatef46723b2012-01-26 14:19:24 -080012570 final long origId = Binder.clearCallingIdentity();
12571 try {
12572 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573
Christopher Tatef46723b2012-01-26 14:19:24 -080012574 synchronized(this) {
12575 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012576 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012577 if (rl != null) {
12578 if (rl.curBroadcast != null) {
12579 BroadcastRecord r = rl.curBroadcast;
12580 final boolean doNext = finishReceiverLocked(
12581 receiver.asBinder(), r.resultCode, r.resultData,
12582 r.resultExtras, r.resultAbort, true);
12583 if (doNext) {
12584 doTrim = true;
12585 r.queue.processNextBroadcast(false);
12586 }
12587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012588
Christopher Tatef46723b2012-01-26 14:19:24 -080012589 if (rl.app != null) {
12590 rl.app.receivers.remove(rl);
12591 }
12592 removeReceiverLocked(rl);
12593 if (rl.linkedToDeath) {
12594 rl.linkedToDeath = false;
12595 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 }
12598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012599
Christopher Tatef46723b2012-01-26 14:19:24 -080012600 // If we actually concluded any broadcasts, we might now be able
12601 // to trim the recipients' apps from our working set
12602 if (doTrim) {
12603 trimApplications();
12604 return;
12605 }
12606
12607 } finally {
12608 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012610 }
12611
12612 void removeReceiverLocked(ReceiverList rl) {
12613 mRegisteredReceivers.remove(rl.receiver.asBinder());
12614 int N = rl.size();
12615 for (int i=0; i<N; i++) {
12616 mReceiverResolver.removeFilter(rl.get(i));
12617 }
12618 }
12619
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012620 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12621 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12622 ProcessRecord r = mLruProcesses.get(i);
12623 if (r.thread != null) {
12624 try {
12625 r.thread.dispatchPackageBroadcast(cmd, packages);
12626 } catch (RemoteException ex) {
12627 }
12628 }
12629 }
12630 }
12631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 private final int broadcastIntentLocked(ProcessRecord callerApp,
12633 String callerPackage, Intent intent, String resolvedType,
12634 IIntentReceiver resultTo, int resultCode, String resultData,
12635 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012636 boolean ordered, boolean sticky, int callingPid, int callingUid,
12637 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 intent = new Intent(intent);
12639
Dianne Hackborne7f97212011-02-24 14:40:20 -080012640 // By default broadcasts do not go to stopped apps.
12641 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12642
Joe Onorato8a9b2202010-02-26 18:56:32 -080012643 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012644 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012645 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012646 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012647 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 }
12649
12650 // Handle special intents: if this broadcast is from the package
12651 // manager about a package being removed, we need to remove all of
12652 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012653 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012654 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012655 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12656 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012657 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658 || uidRemoved) {
12659 if (checkComponentPermission(
12660 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012661 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012662 == PackageManager.PERMISSION_GRANTED) {
12663 if (uidRemoved) {
12664 final Bundle intentExtras = intent.getExtras();
12665 final int uid = intentExtras != null
12666 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12667 if (uid >= 0) {
12668 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12669 synchronized (bs) {
12670 bs.removeUidStatsLocked(uid);
12671 }
12672 }
12673 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012674 // If resources are unvailble just force stop all
12675 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012676 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012677 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12678 if (list != null && (list.length > 0)) {
12679 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012680 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012681 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012682 sendPackageBroadcastLocked(
12683 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012684 }
12685 } else {
12686 Uri data = intent.getData();
12687 String ssp;
12688 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12689 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12690 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012691 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12692 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012693 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012694 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012695 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12696 new String[] {ssp});
12697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012698 }
12699 }
12700 }
12701 } else {
12702 String msg = "Permission Denial: " + intent.getAction()
12703 + " broadcast from " + callerPackage + " (pid=" + callingPid
12704 + ", uid=" + callingUid + ")"
12705 + " requires "
12706 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012707 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708 throw new SecurityException(msg);
12709 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012710
12711 // Special case for adding a package: by default turn on compatibility
12712 // mode.
12713 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012714 Uri data = intent.getData();
12715 String ssp;
12716 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12717 mCompatModePackages.handlePackageAddedLocked(ssp,
12718 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012720 }
12721
12722 /*
12723 * If this is the time zone changed action, queue up a message that will reset the timezone
12724 * of all currently running processes. This message will get queued up before the broadcast
12725 * happens.
12726 */
12727 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12728 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12729 }
12730
Robert Greenwalt03595d02010-11-02 14:08:23 -070012731 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12732 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12733 }
12734
Robert Greenwalt434203a2010-10-11 16:00:27 -070012735 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12736 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12737 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12738 }
12739
Dianne Hackborn854060af2009-07-09 18:14:31 -070012740 /*
12741 * Prevent non-system code (defined here to be non-persistent
12742 * processes) from sending protected broadcasts.
12743 */
12744 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12745 || callingUid == Process.SHELL_UID || callingUid == 0) {
12746 // Always okay.
12747 } else if (callerApp == null || !callerApp.persistent) {
12748 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012749 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012750 intent.getAction())) {
12751 String msg = "Permission Denial: not allowed to send broadcast "
12752 + intent.getAction() + " from pid="
12753 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012754 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012755 throw new SecurityException(msg);
12756 }
12757 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012758 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012759 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012760 }
12761 }
12762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012763 // Add to the sticky list if requested.
12764 if (sticky) {
12765 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12766 callingPid, callingUid)
12767 != PackageManager.PERMISSION_GRANTED) {
12768 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12769 + callingPid + ", uid=" + callingUid
12770 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012771 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012772 throw new SecurityException(msg);
12773 }
12774 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012775 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012776 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012777 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012778 }
12779 if (intent.getComponent() != null) {
12780 throw new SecurityException(
12781 "Sticky broadcasts can't target a specific component");
12782 }
12783 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12784 if (list == null) {
12785 list = new ArrayList<Intent>();
12786 mStickyBroadcasts.put(intent.getAction(), list);
12787 }
12788 int N = list.size();
12789 int i;
12790 for (i=0; i<N; i++) {
12791 if (intent.filterEquals(list.get(i))) {
12792 // This sticky already exists, replace it.
12793 list.set(i, new Intent(intent));
12794 break;
12795 }
12796 }
12797 if (i >= N) {
12798 list.add(new Intent(intent));
12799 }
12800 }
12801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012802 // Figure out who all will receive this broadcast.
12803 List receivers = null;
12804 List<BroadcastFilter> registeredReceivers = null;
12805 try {
12806 if (intent.getComponent() != null) {
12807 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012808 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012809 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012810 if (ai != null) {
12811 receivers = new ArrayList();
12812 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012813 if (isSingleton(ai.processName, ai.applicationInfo)) {
12814 ri.activityInfo = getActivityInfoForUser(ai, 0);
12815 } else {
12816 ri.activityInfo = getActivityInfoForUser(ai, userId);
12817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012818 receivers.add(ri);
12819 }
12820 } else {
12821 // Need to resolve the intent to interested receivers...
12822 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12823 == 0) {
12824 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012825 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012826 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012827 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012828 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12829 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012830 }
12831 } catch (RemoteException ex) {
12832 // pm is in same process, this will never happen.
12833 }
12834
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012835 final boolean replacePending =
12836 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12837
Joe Onorato8a9b2202010-02-26 18:56:32 -080012838 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012839 + " replacePending=" + replacePending);
12840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012841 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12842 if (!ordered && NR > 0) {
12843 // If we are not serializing this broadcast, then send the
12844 // registered receivers separately so they don't wait for the
12845 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012846 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12847 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012848 callerPackage, callingPid, callingUid, requiredPermission,
12849 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012850 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012851 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012852 TAG, "Enqueueing parallel broadcast " + r);
12853 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012854 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012855 queue.enqueueParallelBroadcastLocked(r);
12856 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 registeredReceivers = null;
12859 NR = 0;
12860 }
12861
12862 // Merge into one list.
12863 int ir = 0;
12864 if (receivers != null) {
12865 // A special case for PACKAGE_ADDED: do not allow the package
12866 // being added to see this broadcast. This prevents them from
12867 // using this as a back door to get run as soon as they are
12868 // installed. Maybe in the future we want to have a special install
12869 // broadcast or such for apps, but we'd like to deliberately make
12870 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012871 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012872 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12873 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12874 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012875 Uri data = intent.getData();
12876 if (data != null) {
12877 String pkgName = data.getSchemeSpecificPart();
12878 if (pkgName != null) {
12879 skipPackages = new String[] { pkgName };
12880 }
12881 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012882 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012883 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012884 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012885 if (skipPackages != null && (skipPackages.length > 0)) {
12886 for (String skipPackage : skipPackages) {
12887 if (skipPackage != null) {
12888 int NT = receivers.size();
12889 for (int it=0; it<NT; it++) {
12890 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12891 if (curt.activityInfo.packageName.equals(skipPackage)) {
12892 receivers.remove(it);
12893 it--;
12894 NT--;
12895 }
12896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 }
12898 }
12899 }
12900
12901 int NT = receivers != null ? receivers.size() : 0;
12902 int it = 0;
12903 ResolveInfo curt = null;
12904 BroadcastFilter curr = null;
12905 while (it < NT && ir < NR) {
12906 if (curt == null) {
12907 curt = (ResolveInfo)receivers.get(it);
12908 }
12909 if (curr == null) {
12910 curr = registeredReceivers.get(ir);
12911 }
12912 if (curr.getPriority() >= curt.priority) {
12913 // Insert this broadcast record into the final list.
12914 receivers.add(it, curr);
12915 ir++;
12916 curr = null;
12917 it++;
12918 NT++;
12919 } else {
12920 // Skip to the next ResolveInfo in the final list.
12921 it++;
12922 curt = null;
12923 }
12924 }
12925 }
12926 while (ir < NR) {
12927 if (receivers == null) {
12928 receivers = new ArrayList();
12929 }
12930 receivers.add(registeredReceivers.get(ir));
12931 ir++;
12932 }
12933
12934 if ((receivers != null && receivers.size() > 0)
12935 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012936 BroadcastQueue queue = broadcastQueueForIntent(intent);
12937 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012938 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012939 receivers, resultTo, resultCode, resultData, map, ordered,
12940 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012941 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012943 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944 if (DEBUG_BROADCAST) {
12945 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012946 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012948 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012949 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012950 queue.enqueueOrderedBroadcastLocked(r);
12951 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 }
12954
Dianne Hackborna4972e92012-03-14 10:38:05 -070012955 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012956 }
12957
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012958 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 // Refuse possible leaked file descriptors
12960 if (intent != null && intent.hasFileDescriptors() == true) {
12961 throw new IllegalArgumentException("File descriptors passed in Intent");
12962 }
12963
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012964 int flags = intent.getFlags();
12965
12966 if (!mProcessesReady) {
12967 // if the caller really truly claims to know what they're doing, go
12968 // ahead and allow the broadcast without launching any receivers
12969 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12970 intent = new Intent(intent);
12971 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12972 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12973 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12974 + " before boot completion");
12975 throw new IllegalStateException("Cannot broadcast before boot completed");
12976 }
12977 }
12978
12979 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12980 throw new IllegalArgumentException(
12981 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12982 }
12983
12984 return intent;
12985 }
12986
12987 public final int broadcastIntent(IApplicationThread caller,
12988 Intent intent, String resolvedType, IIntentReceiver resultTo,
12989 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012990 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012991 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012992 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012993 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12996 final int callingPid = Binder.getCallingPid();
12997 final int callingUid = Binder.getCallingUid();
12998 final long origId = Binder.clearCallingIdentity();
12999 int res = broadcastIntentLocked(callerApp,
13000 callerApp != null ? callerApp.info.packageName : null,
13001 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013002 resultCode, resultData, map, requiredPermission, serialized, sticky,
13003 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013004 Binder.restoreCallingIdentity(origId);
13005 return res;
13006 }
13007 }
13008
13009 int broadcastIntentInPackage(String packageName, int uid,
13010 Intent intent, String resolvedType, IIntentReceiver resultTo,
13011 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013012 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013013 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013014 intent = verifyBroadcastLocked(intent);
13015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013016 final long origId = Binder.clearCallingIdentity();
13017 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13018 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013019 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 Binder.restoreCallingIdentity(origId);
13021 return res;
13022 }
13023 }
13024
Amith Yamasani742a6712011-05-04 14:49:28 -070013025 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13026 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013027 // Refuse possible leaked file descriptors
13028 if (intent != null && intent.hasFileDescriptors() == true) {
13029 throw new IllegalArgumentException("File descriptors passed in Intent");
13030 }
13031
13032 synchronized(this) {
13033 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13034 != PackageManager.PERMISSION_GRANTED) {
13035 String msg = "Permission Denial: unbroadcastIntent() from pid="
13036 + Binder.getCallingPid()
13037 + ", uid=" + Binder.getCallingUid()
13038 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013039 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013040 throw new SecurityException(msg);
13041 }
13042 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13043 if (list != null) {
13044 int N = list.size();
13045 int i;
13046 for (i=0; i<N; i++) {
13047 if (intent.filterEquals(list.get(i))) {
13048 list.remove(i);
13049 break;
13050 }
13051 }
13052 }
13053 }
13054 }
13055
13056 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13057 String resultData, Bundle resultExtras, boolean resultAbort,
13058 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013059 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13060 if (r == null) {
13061 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013062 return false;
13063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013064
Christopher Tatef46723b2012-01-26 14:19:24 -080013065 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13066 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013067 }
13068
13069 public void finishReceiver(IBinder who, int resultCode, String resultData,
13070 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013071 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072
13073 // Refuse possible leaked file descriptors
13074 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13075 throw new IllegalArgumentException("File descriptors passed in Bundle");
13076 }
13077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013079 try {
13080 boolean doNext = false;
13081 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082
Christopher Tatef46723b2012-01-26 14:19:24 -080013083 synchronized(this) {
13084 r = broadcastRecordForReceiverLocked(who);
13085 if (r != null) {
13086 doNext = r.queue.finishReceiverLocked(r, resultCode,
13087 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013089 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013090
Christopher Tatef46723b2012-01-26 14:19:24 -080013091 if (doNext) {
13092 r.queue.processNextBroadcast(false);
13093 }
13094 trimApplications();
13095 } finally {
13096 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013100 // =========================================================
13101 // INSTRUMENTATION
13102 // =========================================================
13103
13104 public boolean startInstrumentation(ComponentName className,
13105 String profileFile, int flags, Bundle arguments,
13106 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013107 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013108 // Refuse possible leaked file descriptors
13109 if (arguments != null && arguments.hasFileDescriptors()) {
13110 throw new IllegalArgumentException("File descriptors passed in Bundle");
13111 }
13112
13113 synchronized(this) {
13114 InstrumentationInfo ii = null;
13115 ApplicationInfo ai = null;
13116 try {
13117 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013118 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013119 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013120 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013121 } catch (PackageManager.NameNotFoundException e) {
13122 }
13123 if (ii == null) {
13124 reportStartInstrumentationFailure(watcher, className,
13125 "Unable to find instrumentation info for: " + className);
13126 return false;
13127 }
13128 if (ai == null) {
13129 reportStartInstrumentationFailure(watcher, className,
13130 "Unable to find instrumentation target package: " + ii.targetPackage);
13131 return false;
13132 }
13133
13134 int match = mContext.getPackageManager().checkSignatures(
13135 ii.targetPackage, ii.packageName);
13136 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13137 String msg = "Permission Denial: starting instrumentation "
13138 + className + " from pid="
13139 + Binder.getCallingPid()
13140 + ", uid=" + Binder.getCallingPid()
13141 + " not allowed because package " + ii.packageName
13142 + " does not have a signature matching the target "
13143 + ii.targetPackage;
13144 reportStartInstrumentationFailure(watcher, className, msg);
13145 throw new SecurityException(msg);
13146 }
13147
Amith Yamasani483f3b02012-03-13 16:08:00 -070013148 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013149 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013150 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013151 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013152 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013154 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013155 app.instrumentationProfileFile = profileFile;
13156 app.instrumentationArguments = arguments;
13157 app.instrumentationWatcher = watcher;
13158 app.instrumentationResultClass = className;
13159 Binder.restoreCallingIdentity(origId);
13160 }
13161
13162 return true;
13163 }
13164
13165 /**
13166 * Report errors that occur while attempting to start Instrumentation. Always writes the
13167 * error to the logs, but if somebody is watching, send the report there too. This enables
13168 * the "am" command to report errors with more information.
13169 *
13170 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13171 * @param cn The component name of the instrumentation.
13172 * @param report The error report.
13173 */
13174 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13175 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013176 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 try {
13178 if (watcher != null) {
13179 Bundle results = new Bundle();
13180 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13181 results.putString("Error", report);
13182 watcher.instrumentationStatus(cn, -1, results);
13183 }
13184 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013185 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013186 }
13187 }
13188
13189 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13190 if (app.instrumentationWatcher != null) {
13191 try {
13192 // NOTE: IInstrumentationWatcher *must* be oneway here
13193 app.instrumentationWatcher.instrumentationFinished(
13194 app.instrumentationClass,
13195 resultCode,
13196 results);
13197 } catch (RemoteException e) {
13198 }
13199 }
13200 app.instrumentationWatcher = null;
13201 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013202 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013203 app.instrumentationProfileFile = null;
13204 app.instrumentationArguments = null;
13205
Amith Yamasani483f3b02012-03-13 16:08:00 -070013206 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 }
13208
13209 public void finishInstrumentation(IApplicationThread target,
13210 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013211 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013212 // Refuse possible leaked file descriptors
13213 if (results != null && results.hasFileDescriptors()) {
13214 throw new IllegalArgumentException("File descriptors passed in Intent");
13215 }
13216
13217 synchronized(this) {
13218 ProcessRecord app = getRecordForAppLocked(target);
13219 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013220 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013221 return;
13222 }
13223 final long origId = Binder.clearCallingIdentity();
13224 finishInstrumentationLocked(app, resultCode, results);
13225 Binder.restoreCallingIdentity(origId);
13226 }
13227 }
13228
13229 // =========================================================
13230 // CONFIGURATION
13231 // =========================================================
13232
13233 public ConfigurationInfo getDeviceConfigurationInfo() {
13234 ConfigurationInfo config = new ConfigurationInfo();
13235 synchronized (this) {
13236 config.reqTouchScreen = mConfiguration.touchscreen;
13237 config.reqKeyboardType = mConfiguration.keyboard;
13238 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013239 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13240 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13242 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013243 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13244 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13246 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013247 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 }
13249 return config;
13250 }
13251
13252 public Configuration getConfiguration() {
13253 Configuration ci;
13254 synchronized(this) {
13255 ci = new Configuration(mConfiguration);
13256 }
13257 return ci;
13258 }
13259
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013260 public void updatePersistentConfiguration(Configuration values) {
13261 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13262 "updateConfiguration()");
13263 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13264 "updateConfiguration()");
13265 if (values == null) {
13266 throw new NullPointerException("Configuration must not be null");
13267 }
13268
13269 synchronized(this) {
13270 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013271 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013272 Binder.restoreCallingIdentity(origId);
13273 }
13274 }
13275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276 public void updateConfiguration(Configuration values) {
13277 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13278 "updateConfiguration()");
13279
13280 synchronized(this) {
13281 if (values == null && mWindowManager != null) {
13282 // sentinel: fetch the current configuration from the window manager
13283 values = mWindowManager.computeNewConfiguration();
13284 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013285
13286 if (mWindowManager != null) {
13287 mProcessList.applyDisplaySize(mWindowManager);
13288 }
13289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013290 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013291 if (values != null) {
13292 Settings.System.clearConfiguration(values);
13293 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013294 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013295 Binder.restoreCallingIdentity(origId);
13296 }
13297 }
13298
13299 /**
13300 * Do either or both things: (1) change the current configuration, and (2)
13301 * make sure the given activity is running with the (now) current
13302 * configuration. Returns true if the activity has been left running, or
13303 * false if <var>starting</var> is being destroyed to match the new
13304 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013305 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013307 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013308 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013309 // do nothing if we are headless
13310 if (mHeadless) return true;
13311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 int changes = 0;
13313
13314 boolean kept = true;
13315
13316 if (values != null) {
13317 Configuration newConfig = new Configuration(mConfiguration);
13318 changes = newConfig.updateFrom(values);
13319 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013320 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013321 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013322 }
13323
Doug Zongker2bec3d42009-12-04 12:52:44 -080013324 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013325
Dianne Hackborn813075a62011-11-14 17:45:19 -080013326 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013327 saveLocaleLocked(values.locale,
13328 !values.locale.equals(mConfiguration.locale),
13329 values.userSetLocale);
13330 }
13331
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013332 mConfigurationSeq++;
13333 if (mConfigurationSeq <= 0) {
13334 mConfigurationSeq = 1;
13335 }
13336 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013337 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013338 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013339
13340 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013341
13342 // TODO: If our config changes, should we auto dismiss any currently
13343 // showing dialogs?
13344 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013345
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013346 AttributeCache ac = AttributeCache.instance();
13347 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013348 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013350
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013351 // Make sure all resources in our process are updated
13352 // right now, so that anyone who is going to retrieve
13353 // resource values after we return will be sure to get
13354 // the new ones. This is especially important during
13355 // boot, where the first config change needs to guarantee
13356 // all resources have that config before following boot
13357 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013358 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013359
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013360 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013361 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013362 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013363 mHandler.sendMessage(msg);
13364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013365
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013366 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13367 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013368 try {
13369 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013370 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013371 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013372 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013373 }
13374 } catch (Exception e) {
13375 }
13376 }
13377 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013378 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13379 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013380 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013381 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013382 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13383 broadcastIntentLocked(null, null,
13384 new Intent(Intent.ACTION_LOCALE_CHANGED),
13385 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013386 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013388 }
13389 }
13390
13391 if (changes != 0 && starting == null) {
13392 // If the configuration changed, and the caller is not already
13393 // in the process of starting an activity, then find the top
13394 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013395 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013396 }
13397
13398 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013399 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013400 // And we need to make sure at this point that all other activities
13401 // are made visible with the correct configuration.
13402 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013403 }
13404
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013405 if (values != null && mWindowManager != null) {
13406 mWindowManager.setNewConfiguration(mConfiguration);
13407 }
13408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013409 return kept;
13410 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013411
13412 /**
13413 * Decide based on the configuration whether we should shouw the ANR,
13414 * crash, etc dialogs. The idea is that if there is no affordnace to
13415 * press the on-screen buttons, we shouldn't show the dialog.
13416 *
13417 * A thought: SystemUI might also want to get told about this, the Power
13418 * dialog / global actions also might want different behaviors.
13419 */
13420 private static final boolean shouldShowDialogs(Configuration config) {
13421 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13422 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424
13425 /**
13426 * Save the locale. You must be inside a synchronized (this) block.
13427 */
13428 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13429 if(isDiff) {
13430 SystemProperties.set("user.language", l.getLanguage());
13431 SystemProperties.set("user.region", l.getCountry());
13432 }
13433
13434 if(isPersist) {
13435 SystemProperties.set("persist.sys.language", l.getLanguage());
13436 SystemProperties.set("persist.sys.country", l.getCountry());
13437 SystemProperties.set("persist.sys.localevar", l.getVariant());
13438 }
13439 }
13440
Adam Powelldd8fab22012-03-22 17:47:27 -070013441 @Override
13442 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13443 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013444 return srec != null && srec.task.affinity != null &&
13445 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013446 }
13447
13448 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13449 Intent resultData) {
13450 ComponentName dest = destIntent.getComponent();
13451
13452 synchronized (this) {
13453 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013454 if (srec == null) {
13455 return false;
13456 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013457 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13458 final int start = history.indexOf(srec);
13459 if (start < 0) {
13460 // Current activity is not in history stack; do nothing.
13461 return false;
13462 }
13463 int finishTo = start - 1;
13464 ActivityRecord parent = null;
13465 boolean foundParentInTask = false;
13466 if (dest != null) {
13467 TaskRecord tr = srec.task;
13468 for (int i = start - 1; i >= 0; i--) {
13469 ActivityRecord r = history.get(i);
13470 if (tr != r.task) {
13471 // Couldn't find parent in the same task; stop at the one above this.
13472 // (Root of current task; in-app "home" behavior)
13473 // Always at least finish the current activity.
13474 finishTo = Math.min(start - 1, i + 1);
13475 parent = history.get(finishTo);
13476 break;
13477 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13478 r.info.name.equals(dest.getClassName())) {
13479 finishTo = i;
13480 parent = r;
13481 foundParentInTask = true;
13482 break;
13483 }
13484 }
13485 }
13486
13487 if (mController != null) {
13488 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13489 if (next != null) {
13490 // ask watcher if this is allowed
13491 boolean resumeOK = true;
13492 try {
13493 resumeOK = mController.activityResuming(next.packageName);
13494 } catch (RemoteException e) {
13495 mController = null;
13496 }
13497
13498 if (!resumeOK) {
13499 return false;
13500 }
13501 }
13502 }
13503 final long origId = Binder.clearCallingIdentity();
13504 for (int i = start; i > finishTo; i--) {
13505 ActivityRecord r = history.get(i);
13506 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13507 "navigate-up");
13508 // Only return the supplied result for the first activity finished
13509 resultCode = Activity.RESULT_CANCELED;
13510 resultData = null;
13511 }
13512
13513 if (parent != null && foundParentInTask) {
13514 final int parentLaunchMode = parent.info.launchMode;
13515 final int destIntentFlags = destIntent.getFlags();
13516 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13517 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13518 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13519 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070013520 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070013521 } else {
13522 try {
13523 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13524 destIntent.getComponent(), 0, UserId.getCallingUserId());
13525 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13526 null, aInfo, parent.appToken, null,
13527 0, -1, parent.launchedFromUid, 0, null, true, null);
13528 foundParentInTask = res == ActivityManager.START_SUCCESS;
13529 } catch (RemoteException e) {
13530 foundParentInTask = false;
13531 }
13532 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13533 resultData, "navigate-up");
13534 }
13535 }
13536 Binder.restoreCallingIdentity(origId);
13537 return foundParentInTask;
13538 }
13539 }
13540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013541 // =========================================================
13542 // LIFETIME MANAGEMENT
13543 // =========================================================
13544
Christopher Tatef46723b2012-01-26 14:19:24 -080013545 // Returns which broadcast queue the app is the current [or imminent] receiver
13546 // on, or 'null' if the app is not an active broadcast recipient.
13547 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13548 BroadcastRecord r = app.curReceiver;
13549 if (r != null) {
13550 return r.queue;
13551 }
13552
13553 // It's not the current receiver, but it might be starting up to become one
13554 synchronized (this) {
13555 for (BroadcastQueue queue : mBroadcastQueues) {
13556 r = queue.mPendingBroadcast;
13557 if (r != null && r.curApp == app) {
13558 // found it; report which queue it's in
13559 return queue;
13560 }
13561 }
13562 }
13563
13564 return null;
13565 }
13566
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013567 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013568 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013569 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013570 // This adjustment has already been computed. If we are calling
13571 // from the top, we may have already computed our adjustment with
13572 // an earlier hidden adjustment that isn't really for us... if
13573 // so, use the new hidden adjustment.
13574 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013575 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013576 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013577 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013578 }
13579
13580 if (app.thread == null) {
13581 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013582 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013583 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 }
13585
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013586 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13587 app.adjSource = null;
13588 app.adjTarget = null;
13589 app.empty = false;
13590 app.hidden = false;
13591
13592 final int activitiesSize = app.activities.size();
13593
Dianne Hackborn7d608422011-08-07 16:24:18 -070013594 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013595 // The max adjustment doesn't allow this app to be anything
13596 // below foreground, so it is not worth doing work for it.
13597 app.adjType = "fixed";
13598 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013599 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013600 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013601 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013602 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013603 // System process can do UI, and when they do we want to have
13604 // them trim their memory after the user leaves the UI. To
13605 // facilitate this, here we need to determine whether or not it
13606 // is currently showing UI.
13607 app.systemNoUi = true;
13608 if (app == TOP_APP) {
13609 app.systemNoUi = false;
13610 } else if (activitiesSize > 0) {
13611 for (int j = 0; j < activitiesSize; j++) {
13612 final ActivityRecord r = app.activities.get(j);
13613 if (r.visible) {
13614 app.systemNoUi = false;
13615 break;
13616 }
13617 }
13618 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013619 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013620 }
13621
13622 final boolean hadForegroundActivities = app.foregroundActivities;
13623
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013624 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013625 app.keeping = false;
13626 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013627
The Android Open Source Project4df24232009-03-05 14:34:35 -080013628 // Determine the importance of the process, starting with most
13629 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013630 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013631 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013632 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013633 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013634 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013635 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013636 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013637 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013638 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013639 } else if (app.instrumentationClass != null) {
13640 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013641 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013642 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013643 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013644 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013645 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013646 // counts as being in the foreground for OOM killer purposes.
13647 // It's placed in a sched group based on the nature of the
13648 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013649 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013650 schedGroup = (queue == mFgBroadcastQueue)
13651 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013652 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013653 } else if (app.executingServices.size() > 0) {
13654 // An app that is currently executing a service callback also
13655 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013656 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013657 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013658 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013659 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013660 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013661 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013662 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013663 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013664 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013665 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013666 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013667 // A very not-needed process. If this is lower in the lru list,
13668 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013669 adj = hiddenAdj;
13670 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013671 app.hidden = true;
13672 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013673 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013674 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013675
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013676 boolean hasStoppingActivities = false;
13677
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013678 // Examine all activities if not already foreground.
13679 if (!app.foregroundActivities && activitiesSize > 0) {
13680 for (int j = 0; j < activitiesSize; j++) {
13681 final ActivityRecord r = app.activities.get(j);
13682 if (r.visible) {
13683 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013684 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13685 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013686 app.adjType = "visible";
13687 }
13688 schedGroup = Process.THREAD_GROUP_DEFAULT;
13689 app.hidden = false;
13690 app.foregroundActivities = true;
13691 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013692 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013693 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13694 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013695 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013696 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013697 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013698 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013699 } else if (r.state == ActivityState.STOPPING) {
13700 // We will apply the actual adjustment later, because
13701 // we want to allow this process to immediately go through
13702 // any memory trimming that is in effect.
13703 app.hidden = false;
13704 app.foregroundActivities = true;
13705 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013706 }
13707 }
13708 }
13709
Dianne Hackborn7d608422011-08-07 16:24:18 -070013710 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013711 if (app.foregroundServices) {
13712 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013713 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013714 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013715 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013716 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013717 } else if (app.forcingToForeground != null) {
13718 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013719 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013720 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013721 app.adjType = "force-foreground";
13722 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013723 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013724 }
13725 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013726
Dianne Hackborn7d608422011-08-07 16:24:18 -070013727 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013728 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013729 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013730 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013731 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013732 app.adjType = "heavy";
13733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013734
Dianne Hackborn7d608422011-08-07 16:24:18 -070013735 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013736 // This process is hosting what we currently consider to be the
13737 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013738 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013739 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013740 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013741 app.adjType = "home";
13742 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013743
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013744 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13745 && app.activities.size() > 0) {
13746 // This was the previous process that showed UI to the user.
13747 // We want to try to keep it around more aggressively, to give
13748 // a good experience around switching between two apps.
13749 adj = ProcessList.PREVIOUS_APP_ADJ;
13750 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13751 app.hidden = false;
13752 app.adjType = "previous";
13753 }
13754
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013755 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13756 + " reason=" + app.adjType);
13757
The Android Open Source Project4df24232009-03-05 14:34:35 -080013758 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013759 // there are applications dependent on our services or providers, but
13760 // this gives us a baseline and makes sure we don't get into an
13761 // infinite recursion.
13762 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013763 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013764
Christopher Tate6fa95972009-06-05 18:43:55 -070013765 if (mBackupTarget != null && app == mBackupTarget.app) {
13766 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013767 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013768 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013769 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013770 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013771 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013772 }
13773 }
13774
Dianne Hackborn7d608422011-08-07 16:24:18 -070013775 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013776 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013777 final long now = SystemClock.uptimeMillis();
13778 // This process is more important if the top activity is
13779 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013780 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013781 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013782 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013784 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013785 // If this process has shown some UI, let it immediately
13786 // go to the LRU list because it may be pretty heavy with
13787 // UI stuff. We'll tag it with a label just to help
13788 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013789 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013790 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013791 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013792 } else {
13793 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13794 // This service has seen some activity within
13795 // recent memory, so we will keep its process ahead
13796 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013797 if (adj > ProcessList.SERVICE_ADJ) {
13798 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013799 app.adjType = "started-services";
13800 app.hidden = false;
13801 }
13802 }
13803 // If we have let the service slide into the background
13804 // state, still have some text describing what it is doing
13805 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013806 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013807 app.adjType = "started-bg-services";
13808 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013809 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013810 // Don't kill this process because it is doing work; it
13811 // has said it is doing work.
13812 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013813 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013814 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013815 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013816 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013818 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013819 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013820 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013821 // XXX should compute this based on the max of
13822 // all connected clients.
13823 ConnectionRecord cr = clist.get(i);
13824 if (cr.binding.client == app) {
13825 // Binding to ourself is not interesting.
13826 continue;
13827 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013828 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013829 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013830 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013831 int myHiddenAdj = hiddenAdj;
13832 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013833 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013834 myHiddenAdj = client.hiddenAdj;
13835 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013836 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013837 }
13838 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013839 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013840 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013841 String adjType = null;
13842 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13843 // Not doing bind OOM management, so treat
13844 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013845 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013846 // If this process has shown some UI, let it immediately
13847 // go to the LRU list because it may be pretty heavy with
13848 // UI stuff. We'll tag it with a label just to help
13849 // debug and understand what is going on.
13850 if (adj > clientAdj) {
13851 adjType = "bound-bg-ui-services";
13852 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013853 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013854 clientAdj = adj;
13855 } else {
13856 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13857 // This service has not seen activity within
13858 // recent memory, so allow it to drop to the
13859 // LRU list if there is no other reason to keep
13860 // it around. We'll also tag it with a label just
13861 // to help debug and undertand what is going on.
13862 if (adj > clientAdj) {
13863 adjType = "bound-bg-services";
13864 }
13865 clientAdj = adj;
13866 }
13867 }
13868 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013869 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013870 // If this process has recently shown UI, and
13871 // the process that is binding to it is less
13872 // important than being visible, then we don't
13873 // care about the binding as much as we care
13874 // about letting this process get into the LRU
13875 // list to be killed and restarted if needed for
13876 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013877 if (app.hasShownUi && app != mHomeProcess
13878 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013879 adjType = "bound-bg-ui-services";
13880 } else {
13881 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13882 |Context.BIND_IMPORTANT)) != 0) {
13883 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013884 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13885 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13886 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13887 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13888 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013889 adj = clientAdj;
13890 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013891 app.pendingUiClean = true;
13892 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13893 adj = ProcessList.VISIBLE_APP_ADJ;
13894 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013895 }
13896 if (!client.hidden) {
13897 app.hidden = false;
13898 }
13899 if (client.keeping) {
13900 app.keeping = true;
13901 }
13902 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013903 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013904 }
13905 if (adjType != null) {
13906 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013907 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13908 .REASON_SERVICE_IN_USE;
13909 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013910 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013911 app.adjTarget = s.name;
13912 }
13913 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13914 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13915 schedGroup = Process.THREAD_GROUP_DEFAULT;
13916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013917 }
13918 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013919 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13920 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013921 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013922 (a.visible || a.state == ActivityState.RESUMED
13923 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013924 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013925 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13926 schedGroup = Process.THREAD_GROUP_DEFAULT;
13927 }
13928 app.hidden = false;
13929 app.adjType = "service";
13930 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13931 .REASON_SERVICE_IN_USE;
13932 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013933 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013934 app.adjTarget = s.name;
13935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 }
13938 }
13939 }
13940 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013941
Dianne Hackborn287952c2010-09-22 22:34:31 -070013942 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013943 // would like to avoid killing it unless it would prevent the current
13944 // application from running. By default we put the process in
13945 // with the rest of the background processes; as we scan through
13946 // its services we may bump it up from there.
13947 if (adj > hiddenAdj) {
13948 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013949 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013950 app.adjType = "bg-services";
13951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013952 }
13953
Dianne Hackborn7d608422011-08-07 16:24:18 -070013954 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013955 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013956 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013957 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013958 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013959 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013960 if (cpr.clients.size() != 0) {
13961 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013962 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013963 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013964 if (client == app) {
13965 // Being our own client is not interesting.
13966 continue;
13967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013968 int myHiddenAdj = hiddenAdj;
13969 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013970 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013971 myHiddenAdj = client.hiddenAdj;
13972 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013973 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013974 }
13975 }
13976 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013977 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013978 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013979 if (app.hasShownUi && app != mHomeProcess
13980 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013981 app.adjType = "bg-ui-provider";
13982 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013983 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13984 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013985 app.adjType = "provider";
13986 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013987 if (!client.hidden) {
13988 app.hidden = false;
13989 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013990 if (client.keeping) {
13991 app.keeping = true;
13992 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013993 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13994 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013995 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013996 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013997 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013998 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013999 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14000 schedGroup = Process.THREAD_GROUP_DEFAULT;
14001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014002 }
14003 }
14004 // If the provider has external (non-framework) process
14005 // dependencies, ensure that its adjustment is at least
14006 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080014007 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014008 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14009 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014010 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014011 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014012 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014013 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014014 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014015 }
14016 }
14017 }
14018 }
14019
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014020 if (adj == ProcessList.SERVICE_ADJ) {
14021 if (doingAll) {
14022 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14023 mNewNumServiceProcs++;
14024 }
14025 if (app.serviceb) {
14026 adj = ProcessList.SERVICE_B_ADJ;
14027 }
14028 } else {
14029 app.serviceb = false;
14030 }
14031
14032 app.nonStoppingAdj = adj;
14033
14034 if (hasStoppingActivities) {
14035 // Only upgrade adjustment.
14036 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14037 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14038 app.adjType = "stopping";
14039 }
14040 }
14041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014042 app.curRawAdj = adj;
14043
Joe Onorato8a9b2202010-02-26 18:56:32 -080014044 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014045 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14046 if (adj > app.maxAdj) {
14047 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014048 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014049 schedGroup = Process.THREAD_GROUP_DEFAULT;
14050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014051 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014052 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014053 app.keeping = true;
14054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014055
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014056 if (app.hasAboveClient) {
14057 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14058 // then we need to drop its adjustment to be lower than the service's
14059 // in order to honor the request. We want to drop it by one adjustment
14060 // level... but there is special meaning applied to various levels so
14061 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014062 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014063 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014064 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14065 adj = ProcessList.VISIBLE_APP_ADJ;
14066 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14067 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14068 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14069 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014070 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014071 adj++;
14072 }
14073 }
14074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014075 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014076 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014077
14078 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014079 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14080 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014081 }
14082
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014083 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014084 }
14085
14086 /**
14087 * Ask a given process to GC right now.
14088 */
14089 final void performAppGcLocked(ProcessRecord app) {
14090 try {
14091 app.lastRequestedGc = SystemClock.uptimeMillis();
14092 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014093 if (app.reportLowMemory) {
14094 app.reportLowMemory = false;
14095 app.thread.scheduleLowMemory();
14096 } else {
14097 app.thread.processInBackground();
14098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014099 }
14100 } catch (Exception e) {
14101 // whatever.
14102 }
14103 }
14104
14105 /**
14106 * Returns true if things are idle enough to perform GCs.
14107 */
Josh Bartel7f208742010-02-25 11:01:44 -060014108 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014109 boolean processingBroadcasts = false;
14110 for (BroadcastQueue q : mBroadcastQueues) {
14111 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14112 processingBroadcasts = true;
14113 }
14114 }
14115 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014116 && (mSleeping || (mMainStack.mResumedActivity != null &&
14117 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014118 }
14119
14120 /**
14121 * Perform GCs on all processes that are waiting for it, but only
14122 * if things are idle.
14123 */
14124 final void performAppGcsLocked() {
14125 final int N = mProcessesToGc.size();
14126 if (N <= 0) {
14127 return;
14128 }
Josh Bartel7f208742010-02-25 11:01:44 -060014129 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014130 while (mProcessesToGc.size() > 0) {
14131 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014132 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014133 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14134 <= SystemClock.uptimeMillis()) {
14135 // To avoid spamming the system, we will GC processes one
14136 // at a time, waiting a few seconds between each.
14137 performAppGcLocked(proc);
14138 scheduleAppGcsLocked();
14139 return;
14140 } else {
14141 // It hasn't been long enough since we last GCed this
14142 // process... put it in the list to wait for its time.
14143 addProcessToGcListLocked(proc);
14144 break;
14145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014146 }
14147 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014148
14149 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014150 }
14151 }
14152
14153 /**
14154 * If all looks good, perform GCs on all processes waiting for them.
14155 */
14156 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014157 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014158 performAppGcsLocked();
14159 return;
14160 }
14161 // Still not idle, wait some more.
14162 scheduleAppGcsLocked();
14163 }
14164
14165 /**
14166 * Schedule the execution of all pending app GCs.
14167 */
14168 final void scheduleAppGcsLocked() {
14169 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014170
14171 if (mProcessesToGc.size() > 0) {
14172 // Schedule a GC for the time to the next process.
14173 ProcessRecord proc = mProcessesToGc.get(0);
14174 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14175
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014176 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014177 long now = SystemClock.uptimeMillis();
14178 if (when < (now+GC_TIMEOUT)) {
14179 when = now + GC_TIMEOUT;
14180 }
14181 mHandler.sendMessageAtTime(msg, when);
14182 }
14183 }
14184
14185 /**
14186 * Add a process to the array of processes waiting to be GCed. Keeps the
14187 * list in sorted order by the last GC time. The process can't already be
14188 * on the list.
14189 */
14190 final void addProcessToGcListLocked(ProcessRecord proc) {
14191 boolean added = false;
14192 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14193 if (mProcessesToGc.get(i).lastRequestedGc <
14194 proc.lastRequestedGc) {
14195 added = true;
14196 mProcessesToGc.add(i+1, proc);
14197 break;
14198 }
14199 }
14200 if (!added) {
14201 mProcessesToGc.add(0, proc);
14202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014203 }
14204
14205 /**
14206 * Set up to ask a process to GC itself. This will either do it
14207 * immediately, or put it on the list of processes to gc the next
14208 * time things are idle.
14209 */
14210 final void scheduleAppGcLocked(ProcessRecord app) {
14211 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014212 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014213 return;
14214 }
14215 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014216 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014217 scheduleAppGcsLocked();
14218 }
14219 }
14220
Dianne Hackborn287952c2010-09-22 22:34:31 -070014221 final void checkExcessivePowerUsageLocked(boolean doKills) {
14222 updateCpuStatsNow();
14223
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014224 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014225 boolean doWakeKills = doKills;
14226 boolean doCpuKills = doKills;
14227 if (mLastPowerCheckRealtime == 0) {
14228 doWakeKills = false;
14229 }
14230 if (mLastPowerCheckUptime == 0) {
14231 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014232 }
14233 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014234 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014235 }
14236 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014237 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14238 final long curUptime = SystemClock.uptimeMillis();
14239 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14240 mLastPowerCheckRealtime = curRealtime;
14241 mLastPowerCheckUptime = curUptime;
14242 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14243 doWakeKills = false;
14244 }
14245 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14246 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014247 }
14248 int i = mLruProcesses.size();
14249 while (i > 0) {
14250 i--;
14251 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014252 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014253 long wtime;
14254 synchronized (stats) {
14255 wtime = stats.getProcessWakeTime(app.info.uid,
14256 app.pid, curRealtime);
14257 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014258 long wtimeUsed = wtime - app.lastWakeTime;
14259 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14260 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014261 StringBuilder sb = new StringBuilder(128);
14262 sb.append("Wake for ");
14263 app.toShortString(sb);
14264 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014265 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014266 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014267 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014268 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014269 sb.append((wtimeUsed*100)/realtimeSince);
14270 sb.append("%)");
14271 Slog.i(TAG, sb.toString());
14272 sb.setLength(0);
14273 sb.append("CPU for ");
14274 app.toShortString(sb);
14275 sb.append(": over ");
14276 TimeUtils.formatDuration(uptimeSince, sb);
14277 sb.append(" used ");
14278 TimeUtils.formatDuration(cputimeUsed, sb);
14279 sb.append(" (");
14280 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014281 sb.append("%)");
14282 Slog.i(TAG, sb.toString());
14283 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014284 // If a process has held a wake lock for more
14285 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014286 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014287 if (doWakeKills && realtimeSince > 0
14288 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14289 synchronized (stats) {
14290 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14291 realtimeSince, wtimeUsed);
14292 }
14293 Slog.w(TAG, "Excessive wake lock in " + app.processName
14294 + " (pid " + app.pid + "): held " + wtimeUsed
14295 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014296 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14297 app.processName, app.setAdj, "excessive wake lock");
14298 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014299 } else if (doCpuKills && uptimeSince > 0
14300 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14301 synchronized (stats) {
14302 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14303 uptimeSince, cputimeUsed);
14304 }
14305 Slog.w(TAG, "Excessive CPU in " + app.processName
14306 + " (pid " + app.pid + "): used " + cputimeUsed
14307 + " during " + uptimeSince);
14308 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14309 app.processName, app.setAdj, "excessive cpu");
14310 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014311 } else {
14312 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014313 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014314 }
14315 }
14316 }
14317 }
14318
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014319 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014320 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014321 app.hiddenAdj = hiddenAdj;
14322
14323 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014324 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014325 }
14326
Dianne Hackborn287952c2010-09-22 22:34:31 -070014327 final boolean wasKeeping = app.keeping;
14328
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014329 boolean success = true;
14330
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014331 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014332
Jeff Brown10e89712011-07-08 18:52:57 -070014333 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014334 if (wasKeeping && !app.keeping) {
14335 // This app is no longer something we want to keep. Note
14336 // its current wake lock time to later know to kill it if
14337 // it is not behaving well.
14338 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14339 synchronized (stats) {
14340 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14341 app.pid, SystemClock.elapsedRealtime());
14342 }
14343 app.lastCpuTime = app.curCpuTime;
14344 }
14345
14346 app.setRawAdj = app.curRawAdj;
14347 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014348
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014349 if (app.curAdj != app.setAdj) {
14350 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014351 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014352 TAG, "Set " + app.pid + " " + app.processName +
14353 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014354 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014355 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014356 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014357 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014358 }
14359 }
14360 if (app.setSchedGroup != app.curSchedGroup) {
14361 app.setSchedGroup = app.curSchedGroup;
14362 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14363 "Setting process group of " + app.processName
14364 + " to " + app.curSchedGroup);
14365 if (app.waitingToKill != null &&
14366 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14367 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14368 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14369 app.processName, app.setAdj, app.waitingToKill);
14370 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014371 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014372 } else {
14373 if (true) {
14374 long oldId = Binder.clearCallingIdentity();
14375 try {
14376 Process.setProcessGroup(app.pid, app.curSchedGroup);
14377 } catch (Exception e) {
14378 Slog.w(TAG, "Failed setting process group of " + app.pid
14379 + " to " + app.curSchedGroup);
14380 e.printStackTrace();
14381 } finally {
14382 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014383 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014384 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014385 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014386 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014387 app.thread.setSchedulingGroup(app.curSchedGroup);
14388 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014389 }
14390 }
14391 }
14392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014393 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014394 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014395 }
14396
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014397 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014398 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014399 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014400 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014401 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014402 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014403 }
14404 }
14405 return resumedActivity;
14406 }
14407
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014408 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014409 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014410 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14411 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014412 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14413 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014414
14415 mAdjSeq++;
14416
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014417 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014418 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14419 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014420 if (nowHidden != wasHidden) {
14421 // Changed to/from hidden state, so apps after it in the LRU
14422 // list may also be changed.
14423 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014424 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014425 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014426 }
14427
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014428 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014429 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014430 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14431
14432 if (false) {
14433 RuntimeException e = new RuntimeException();
14434 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014435 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014436 }
14437
14438 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014439 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014440
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014441 // Let's determine how many processes we have running vs.
14442 // how many slots we have for background processes; we may want
14443 // to put multiple processes in a slot of there are enough of
14444 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014445 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014446 int factor = (mLruProcesses.size()-4)/numSlots;
14447 if (factor < 1) factor = 1;
14448 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014449 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014450 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014451
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014452 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014453 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014454 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014455 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014456 while (i > 0) {
14457 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014458 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014459 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014460 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14461 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014462 && app.curAdj == curHiddenAdj) {
14463 step++;
14464 if (step >= factor) {
14465 step = 0;
14466 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014467 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014468 }
14469 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014470 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014471 numHidden++;
14472 if (numHidden > mProcessLimit) {
14473 Slog.i(TAG, "No longer want " + app.processName
14474 + " (pid " + app.pid + "): hidden #" + numHidden);
14475 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14476 app.processName, app.setAdj, "too many background");
14477 app.killedBackground = true;
14478 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014479 }
14480 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014481 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14482 // If this is an isolated process, and there are no
14483 // services running in it, then the process is no longer
14484 // needed. We agressively kill these because we can by
14485 // definition not re-use the same process again, and it is
14486 // good to avoid having whatever code was running in them
14487 // left sitting around after no longer needed.
14488 Slog.i(TAG, "Isolated process " + app.processName
14489 + " (pid " + app.pid + ") no longer needed");
14490 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14491 app.processName, app.setAdj, "isolated not needed");
14492 app.killedBackground = true;
14493 Process.killProcessQuiet(app.pid);
14494 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014495 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14496 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14497 && !app.killedBackground) {
14498 numTrimming++;
14499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014500 }
14501 }
14502
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014503 mNumServiceProcs = mNewNumServiceProcs;
14504
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014505 // Now determine the memory trimming level of background processes.
14506 // Unfortunately we need to start at the back of the list to do this
14507 // properly. We only do this if the number of background apps we
14508 // are managing to keep around is less than half the maximum we desire;
14509 // if we are keeping a good number around, we'll let them use whatever
14510 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014511 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014512 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014513 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014514 int minFactor = 2;
14515 if (mHomeProcess != null) minFactor++;
14516 if (mPreviousProcess != null) minFactor++;
14517 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014518 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014519 int fgTrimLevel;
14520 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14521 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14522 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14523 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14524 } else {
14525 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14526 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014527 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014528 for (i=0; i<N; i++) {
14529 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014530 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14531 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014532 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014533 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14534 try {
14535 app.thread.scheduleTrimMemory(curLevel);
14536 } catch (RemoteException e) {
14537 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014538 if (false) {
14539 // For now we won't do this; our memory trimming seems
14540 // to be good enough at this point that destroying
14541 // activities causes more harm than good.
14542 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14543 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014544 // Need to do this on its own message because the stack may not
14545 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014546 // For these apps we will also finish their activities
14547 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014548 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014549 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014550 }
14551 }
14552 app.trimMemoryLevel = curLevel;
14553 step++;
14554 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014555 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014556 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014557 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14558 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014559 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014560 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14561 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014562 break;
14563 }
14564 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014565 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014566 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014567 && app.thread != null) {
14568 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014569 app.thread.scheduleTrimMemory(
14570 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014571 } catch (RemoteException e) {
14572 }
14573 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014574 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014575 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014576 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014577 && app.pendingUiClean) {
14578 // If this application is now in the background and it
14579 // had done UI, then give it the special trim level to
14580 // have it free UI resources.
14581 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14582 if (app.trimMemoryLevel < level && app.thread != null) {
14583 try {
14584 app.thread.scheduleTrimMemory(level);
14585 } catch (RemoteException e) {
14586 }
14587 }
14588 app.pendingUiClean = false;
14589 }
14590 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014591 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014592 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014593 } catch (RemoteException e) {
14594 }
14595 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014596 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014597 }
14598 }
14599 } else {
14600 final int N = mLruProcesses.size();
14601 for (i=0; i<N; i++) {
14602 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014603 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014604 && app.pendingUiClean) {
14605 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14606 && app.thread != null) {
14607 try {
14608 app.thread.scheduleTrimMemory(
14609 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14610 } catch (RemoteException e) {
14611 }
14612 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014613 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014614 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014615 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014616 }
14617 }
14618
14619 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014620 // Need to do this on its own message because the stack may not
14621 // be in a consistent state at this point.
14622 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014624 }
14625
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014626 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014627 synchronized (this) {
14628 int i;
14629
14630 // First remove any unused application processes whose package
14631 // has been removed.
14632 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14633 final ProcessRecord app = mRemovedProcesses.get(i);
14634 if (app.activities.size() == 0
14635 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014636 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014637 TAG, "Exiting empty application process "
14638 + app.processName + " ("
14639 + (app.thread != null ? app.thread.asBinder() : null)
14640 + ")\n");
14641 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014642 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14643 app.processName, app.setAdj, "empty");
14644 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014645 } else {
14646 try {
14647 app.thread.scheduleExit();
14648 } catch (Exception e) {
14649 // Ignore exceptions.
14650 }
14651 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014652 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014653 mRemovedProcesses.remove(i);
14654
14655 if (app.persistent) {
14656 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014657 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014658 }
14659 }
14660 }
14661 }
14662
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014663 // Now update the oom adj for all processes.
14664 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014665 }
14666 }
14667
14668 /** This method sends the specified signal to each of the persistent apps */
14669 public void signalPersistentProcesses(int sig) throws RemoteException {
14670 if (sig != Process.SIGNAL_USR1) {
14671 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14672 }
14673
14674 synchronized (this) {
14675 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14676 != PackageManager.PERMISSION_GRANTED) {
14677 throw new SecurityException("Requires permission "
14678 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14679 }
14680
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014681 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14682 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014683 if (r.thread != null && r.persistent) {
14684 Process.sendSignal(r.pid, sig);
14685 }
14686 }
14687 }
14688 }
14689
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014690 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14691 if (proc == null || proc == mProfileProc) {
14692 proc = mProfileProc;
14693 path = mProfileFile;
14694 profileType = mProfileType;
14695 clearProfilerLocked();
14696 }
14697 if (proc == null) {
14698 return;
14699 }
14700 try {
14701 proc.thread.profilerControl(false, path, null, profileType);
14702 } catch (RemoteException e) {
14703 throw new IllegalStateException("Process disappeared");
14704 }
14705 }
14706
14707 private void clearProfilerLocked() {
14708 if (mProfileFd != null) {
14709 try {
14710 mProfileFd.close();
14711 } catch (IOException e) {
14712 }
14713 }
14714 mProfileApp = null;
14715 mProfileProc = null;
14716 mProfileFile = null;
14717 mProfileType = 0;
14718 mAutoStopProfiler = false;
14719 }
14720
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014721 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014722 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014723
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014724 try {
14725 synchronized (this) {
14726 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14727 // its own permission.
14728 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14729 != PackageManager.PERMISSION_GRANTED) {
14730 throw new SecurityException("Requires permission "
14731 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014732 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014733
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014734 if (start && fd == null) {
14735 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014736 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014737
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014738 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014739 if (process != null) {
14740 try {
14741 int pid = Integer.parseInt(process);
14742 synchronized (mPidsSelfLocked) {
14743 proc = mPidsSelfLocked.get(pid);
14744 }
14745 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014746 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014747
14748 if (proc == null) {
14749 HashMap<String, SparseArray<ProcessRecord>> all
14750 = mProcessNames.getMap();
14751 SparseArray<ProcessRecord> procs = all.get(process);
14752 if (procs != null && procs.size() > 0) {
14753 proc = procs.valueAt(0);
14754 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014755 }
14756 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014757
14758 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014759 throw new IllegalArgumentException("Unknown process: " + process);
14760 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014761
14762 if (start) {
14763 stopProfilerLocked(null, null, 0);
14764 setProfileApp(proc.info, proc.processName, path, fd, false);
14765 mProfileProc = proc;
14766 mProfileType = profileType;
14767 try {
14768 fd = fd.dup();
14769 } catch (IOException e) {
14770 fd = null;
14771 }
14772 proc.thread.profilerControl(start, path, fd, profileType);
14773 fd = null;
14774 mProfileFd = null;
14775 } else {
14776 stopProfilerLocked(proc, path, profileType);
14777 if (fd != null) {
14778 try {
14779 fd.close();
14780 } catch (IOException e) {
14781 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014782 }
14783 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014784
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014785 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014786 }
14787 } catch (RemoteException e) {
14788 throw new IllegalStateException("Process disappeared");
14789 } finally {
14790 if (fd != null) {
14791 try {
14792 fd.close();
14793 } catch (IOException e) {
14794 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014795 }
14796 }
14797 }
Andy McFadden824c5102010-07-09 16:26:57 -070014798
14799 public boolean dumpHeap(String process, boolean managed,
14800 String path, ParcelFileDescriptor fd) throws RemoteException {
14801
14802 try {
14803 synchronized (this) {
14804 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14805 // its own permission (same as profileControl).
14806 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14807 != PackageManager.PERMISSION_GRANTED) {
14808 throw new SecurityException("Requires permission "
14809 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14810 }
14811
14812 if (fd == null) {
14813 throw new IllegalArgumentException("null fd");
14814 }
14815
14816 ProcessRecord proc = null;
14817 try {
14818 int pid = Integer.parseInt(process);
14819 synchronized (mPidsSelfLocked) {
14820 proc = mPidsSelfLocked.get(pid);
14821 }
14822 } catch (NumberFormatException e) {
14823 }
14824
14825 if (proc == null) {
14826 HashMap<String, SparseArray<ProcessRecord>> all
14827 = mProcessNames.getMap();
14828 SparseArray<ProcessRecord> procs = all.get(process);
14829 if (procs != null && procs.size() > 0) {
14830 proc = procs.valueAt(0);
14831 }
14832 }
14833
14834 if (proc == null || proc.thread == null) {
14835 throw new IllegalArgumentException("Unknown process: " + process);
14836 }
14837
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014838 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14839 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014840 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14841 throw new SecurityException("Process not debuggable: " + proc);
14842 }
14843 }
14844
14845 proc.thread.dumpHeap(managed, path, fd);
14846 fd = null;
14847 return true;
14848 }
14849 } catch (RemoteException e) {
14850 throw new IllegalStateException("Process disappeared");
14851 } finally {
14852 if (fd != null) {
14853 try {
14854 fd.close();
14855 } catch (IOException e) {
14856 }
14857 }
14858 }
14859 }
14860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014861 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14862 public void monitor() {
14863 synchronized (this) { }
14864 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014865
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014866 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014867 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14868 ProcessRecord processRecord = mLruProcesses.get(i);
14869 try {
14870 if (processRecord.thread != null) {
14871 processRecord.thread.setCoreSettings(settings);
14872 }
14873 } catch (RemoteException re) {
14874 /* ignore */
14875 }
14876 }
14877 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014878
14879 // Multi-user methods
14880
Amith Yamasani742a6712011-05-04 14:49:28 -070014881 private int mCurrentUserId;
14882 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14883
14884 public boolean switchUser(int userId) {
14885 final int callingUid = Binder.getCallingUid();
14886 if (callingUid != 0 && callingUid != Process.myUid()) {
14887 Slog.e(TAG, "Trying to switch user from unauthorized app");
14888 return false;
14889 }
14890 if (mCurrentUserId == userId)
14891 return true;
14892
14893 synchronized (this) {
14894 // Check if user is already logged in, otherwise check if user exists first before
14895 // adding to the list of logged in users.
14896 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14897 if (!userExists(userId)) {
14898 return false;
14899 }
14900 mLoggedInUsers.append(userId, userId);
14901 }
14902
14903 mCurrentUserId = userId;
14904 boolean haveActivities = mMainStack.switchUser(userId);
14905 if (!haveActivities) {
14906 startHomeActivityLocked(userId);
14907 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014908
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014909 }
Amith Yamasani13593602012-03-22 16:16:17 -070014910
14911 // Inform of user switch
14912 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14913 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14914 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14915
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014916 return true;
14917 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014918
Amith Yamasani52f1d752012-03-28 18:19:29 -070014919 @Override
14920 public UserInfo getCurrentUser() throws RemoteException {
14921 final int callingUid = Binder.getCallingUid();
14922 if (callingUid != 0 && callingUid != Process.myUid()) {
14923 Slog.e(TAG, "Trying to get user from unauthorized app");
14924 return null;
14925 }
14926 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14927 }
14928
Amith Yamasani13593602012-03-22 16:16:17 -070014929 private void onUserRemoved(Intent intent) {
14930 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14931 if (extraUserId < 1) return;
14932
14933 // Kill all the processes for the user
14934 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14935 synchronized (this) {
14936 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14937 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14938 SparseArray<ProcessRecord> uids = uidMap.getValue();
14939 for (int i = 0; i < uids.size(); i++) {
14940 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14941 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14942 }
14943 }
14944 }
14945
14946 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14947 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14948 false, false, true, true, extraUserId);
14949 }
14950 }
14951 }
14952
Amith Yamasani742a6712011-05-04 14:49:28 -070014953 private boolean userExists(int userId) {
14954 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014955 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14956 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014957 } catch (RemoteException re) {
14958 // Won't happen, in same process
14959 }
14960
14961 return false;
14962 }
14963
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014964 private void checkValidCaller(int uid, int userId) {
14965 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14966
14967 throw new SecurityException("Caller uid=" + uid
14968 + " is not privileged to communicate with user=" + userId);
14969 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014970
14971 private int applyUserId(int uid, int userId) {
14972 return UserId.getUid(userId, uid);
14973 }
14974
14975 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014976 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014977 ApplicationInfo newInfo = new ApplicationInfo(info);
14978 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014979 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14980 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014981 return newInfo;
14982 }
14983
14984 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014985 if (aInfo == null
14986 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014987 return aInfo;
14988 }
14989
14990 ActivityInfo info = new ActivityInfo(aInfo);
14991 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14992 return info;
14993 }
14994
14995 static class ServiceMap {
14996
14997 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14998 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14999 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15000 mServicesByIntentPerUser = new SparseArray<
15001 HashMap<Intent.FilterComparison, ServiceRecord>>();
15002
15003 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15004 // TODO: Deal with global services
15005 if (DEBUG_MU)
15006 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15007 return getServices(callingUser).get(name);
15008 }
15009
15010 ServiceRecord getServiceByName(ComponentName name) {
15011 return getServiceByName(name, -1);
15012 }
15013
15014 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15015 // TODO: Deal with global services
15016 if (DEBUG_MU)
15017 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15018 return getServicesByIntent(callingUser).get(filter);
15019 }
15020
15021 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15022 return getServiceByIntent(filter, -1);
15023 }
15024
15025 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15026 // TODO: Deal with global services
15027 getServices(callingUser).put(name, value);
15028 }
15029
15030 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15031 ServiceRecord value) {
15032 // TODO: Deal with global services
15033 getServicesByIntent(callingUser).put(filter, value);
15034 }
15035
15036 void removeServiceByName(ComponentName name, int callingUser) {
15037 // TODO: Deal with global services
15038 ServiceRecord removed = getServices(callingUser).remove(name);
15039 if (DEBUG_MU)
15040 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15041 + " removed=" + removed);
15042 }
15043
15044 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15045 // TODO: Deal with global services
15046 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15047 if (DEBUG_MU)
15048 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15049 + " removed=" + removed);
15050 }
15051
15052 Collection<ServiceRecord> getAllServices(int callingUser) {
15053 // TODO: Deal with global services
15054 return getServices(callingUser).values();
15055 }
15056
15057 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15058 HashMap map = mServicesByNamePerUser.get(callingUser);
15059 if (map == null) {
15060 map = new HashMap<ComponentName, ServiceRecord>();
15061 mServicesByNamePerUser.put(callingUser, map);
15062 }
15063 return map;
15064 }
15065
15066 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15067 int callingUser) {
15068 HashMap map = mServicesByIntentPerUser.get(callingUser);
15069 if (map == null) {
15070 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15071 mServicesByIntentPerUser.put(callingUser, map);
15072 }
15073 return map;
15074 }
15075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015076}