blob: 76016f46fa0c6601fc32f2bdb2f6c3a51b9c72fb [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 Hackborne302a162012-05-15 14:58:32 -07003513
3514 final int uid = Binder.getCallingUid();
3515 final long origId = Binder.clearCallingIdentity();
3516 synchronized (this) {
3517 closeSystemDialogsLocked(uid, reason);
3518 }
3519 Binder.restoreCallingIdentity(origId);
3520 }
3521
3522 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003523 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003524 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003525 if (reason != null) {
3526 intent.putExtra("reason", reason);
3527 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003528 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003529
Dianne Hackborne302a162012-05-15 14:58:32 -07003530 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3531 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
3532 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
3533 r.stack.finishActivityLocked(r, i,
3534 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003535 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003536 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003537
3538 broadcastIntentLocked(null, null, intent, null,
3539 null, 0, null, null, null, false, false, -1,
3540 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003541 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003542
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003543 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003544 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003545 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003546 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3547 for (int i=pids.length-1; i>=0; i--) {
3548 infos[i] = new Debug.MemoryInfo();
3549 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003550 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003551 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003552 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003553
Dianne Hackbornb437e092011-08-05 17:50:29 -07003554 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003555 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003556 long[] pss = new long[pids.length];
3557 for (int i=pids.length-1; i>=0; i--) {
3558 pss[i] = Debug.getPss(pids[i]);
3559 }
3560 return pss;
3561 }
3562
Christopher Tate5e1ab332009-09-01 20:32:49 -07003563 public void killApplicationProcess(String processName, int uid) {
3564 if (processName == null) {
3565 return;
3566 }
3567
3568 int callerUid = Binder.getCallingUid();
3569 // Only the system server can kill an application
3570 if (callerUid == Process.SYSTEM_UID) {
3571 synchronized (this) {
3572 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003573 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003574 try {
3575 app.thread.scheduleSuicide();
3576 } catch (RemoteException e) {
3577 // If the other end already died, then our work here is done.
3578 }
3579 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003580 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003581 + processName + " / " + uid);
3582 }
3583 }
3584 } else {
3585 throw new SecurityException(callerUid + " cannot kill app process: " +
3586 processName);
3587 }
3588 }
3589
Dianne Hackborn03abb812010-01-04 18:43:19 -08003590 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003591 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3593 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003594 if (!mProcessesReady) {
3595 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 intent.putExtra(Intent.EXTRA_UID, uid);
3598 broadcastIntentLocked(null, null, intent,
3599 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003600 false, false,
3601 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 }
3603
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003604 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003605 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003606 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003607 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608
Dianne Hackborn03abb812010-01-04 18:43:19 -08003609 // Remove all processes this package may have touched: all with the
3610 // same UID (except for the system or root user), and all whose name
3611 // matches the package name.
3612 final String procNamePrefix = packageName + ":";
3613 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3614 final int NA = apps.size();
3615 for (int ia=0; ia<NA; ia++) {
3616 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003617 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003618 // we don't kill persistent processes
3619 continue;
3620 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003621 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003622 if (doit) {
3623 procs.add(app);
3624 }
Amith Yamasani13593602012-03-22 16:16:17 -07003625 // If uid is specified and the uid and process name match
3626 // Or, the uid is not specified and the process name matches
3627 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003628 || ((app.processName.equals(packageName)
3629 || app.processName.startsWith(procNamePrefix))
3630 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003631 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003632 if (!doit) {
3633 return true;
3634 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003635 app.removed = true;
3636 procs.add(app);
3637 }
3638 }
3639 }
3640 }
3641
3642 int N = procs.size();
3643 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003644 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003645 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003646 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003647 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003648
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003649 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003650 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003651 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003652 int i;
3653 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 if (uid < 0) {
3656 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003657 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 } catch (RemoteException e) {
3659 }
3660 }
3661
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003662 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003663 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003664
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003665 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3666 while (badApps.hasNext()) {
3667 SparseArray<Long> ba = badApps.next();
3668 if (ba.get(uid) != null) {
3669 badApps.remove();
3670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 }
3672 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003673
3674 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003675 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003677 TaskRecord lastTask = null;
3678 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003679 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003680 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003681 if (r.userId == userId
3682 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003683 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003684 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003685 if (r.finishing) {
3686 // If this activity is just finishing, then it is not
3687 // interesting as far as something to stop.
3688 continue;
3689 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003690 return true;
3691 }
3692 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003693 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003694 if (samePackage) {
3695 if (r.app != null) {
3696 r.app.removed = true;
3697 }
3698 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003700 lastTask = r.task;
3701 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003702 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003703 i--;
3704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 }
3706 }
3707
3708 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003709 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003710 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003711 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003712 if (!doit) {
3713 return true;
3714 }
3715 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003716 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 if (service.app != null) {
3718 service.app.removed = true;
3719 }
3720 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003721 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 services.add(service);
3723 }
3724 }
3725
3726 N = services.size();
3727 for (i=0; i<N; i++) {
3728 bringDownServiceLocked(services.get(i), true);
3729 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003730
3731 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003732 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003733 if (provider.info.packageName.equals(name)
3734 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3735 if (!doit) {
3736 return true;
3737 }
3738 didSomething = true;
3739 providers.add(provider);
3740 }
3741 }
3742
3743 N = providers.size();
3744 for (i=0; i<N; i++) {
3745 removeDyingProviderLocked(null, providers.get(i));
3746 }
3747
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003748 if (doit) {
3749 if (purgeCache) {
3750 AttributeCache ac = AttributeCache.instance();
3751 if (ac != null) {
3752 ac.removePackage(name);
3753 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003754 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003755 if (mBooted) {
3756 mMainStack.resumeTopActivityLocked(null);
3757 mMainStack.scheduleIdleLocked();
3758 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003759 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003760
3761 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 }
3763
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003764 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003765 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003767 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003768 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003769 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 + "/" + uid + ")");
3771
3772 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003773 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003774 if (mHeavyWeightProcess == app) {
3775 mHeavyWeightProcess = null;
3776 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 boolean needRestart = false;
3779 if (app.pid > 0 && app.pid != MY_PID) {
3780 int pid = app.pid;
3781 synchronized (mPidsSelfLocked) {
3782 mPidsSelfLocked.remove(pid);
3783 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3784 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003785 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003786 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003787 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003788 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003790 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003792 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 } else {
3794 needRestart = true;
3795 }
3796 }
3797 } else {
3798 mRemovedProcesses.add(app);
3799 }
3800
3801 return needRestart;
3802 }
3803
3804 private final void processStartTimedOutLocked(ProcessRecord app) {
3805 final int pid = app.pid;
3806 boolean gone = false;
3807 synchronized (mPidsSelfLocked) {
3808 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3809 if (knownApp != null && knownApp.thread == null) {
3810 mPidsSelfLocked.remove(pid);
3811 gone = true;
3812 }
3813 }
3814
3815 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003816 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003817 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003818 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003819 mProcessNames.remove(app.processName, app.uid);
3820 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003821 if (mHeavyWeightProcess == app) {
3822 mHeavyWeightProcess = null;
3823 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3824 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003825 // Take care of any launching providers waiting for this process.
3826 checkAppInLaunchingProvidersLocked(app, true);
3827 // Take care of any services that are waiting for the process.
3828 for (int i=0; i<mPendingServices.size(); i++) {
3829 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003830 if ((app.uid == sr.appInfo.uid
3831 && app.processName.equals(sr.processName))
3832 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003833 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003834 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003835 mPendingServices.remove(i);
3836 i--;
3837 bringDownServiceLocked(sr, true);
3838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003840 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3841 app.processName, app.setAdj, "start timeout");
3842 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003843 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003844 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003845 try {
3846 IBackupManager bm = IBackupManager.Stub.asInterface(
3847 ServiceManager.getService(Context.BACKUP_SERVICE));
3848 bm.agentDisconnected(app.info.packageName);
3849 } catch (RemoteException e) {
3850 // Can't happen; the backup manager is local
3851 }
3852 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003853 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003854 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003855 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003858 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
3860 }
3861
3862 private final boolean attachApplicationLocked(IApplicationThread thread,
3863 int pid) {
3864
3865 // Find the application record that is being attached... either via
3866 // the pid if we are running in multiple processes, or just pull the
3867 // next app record if we are emulating process with anonymous threads.
3868 ProcessRecord app;
3869 if (pid != MY_PID && pid >= 0) {
3870 synchronized (mPidsSelfLocked) {
3871 app = mPidsSelfLocked.get(pid);
3872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 } else {
3874 app = null;
3875 }
3876
3877 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003878 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003880 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003882 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 } else {
3884 try {
3885 thread.scheduleExit();
3886 } catch (Exception e) {
3887 // Ignore exceptions.
3888 }
3889 }
3890 return false;
3891 }
3892
3893 // If this application record is still attached to a previous
3894 // process, clean it up now.
3895 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003896 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
3898
3899 // Tell the process all about itself.
3900
Joe Onorato8a9b2202010-02-26 18:56:32 -08003901 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 TAG, "Binding process pid " + pid + " to record " + app);
3903
3904 String processName = app.processName;
3905 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003906 AppDeathRecipient adr = new AppDeathRecipient(
3907 app, pid, thread);
3908 thread.asBinder().linkToDeath(adr, 0);
3909 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 } catch (RemoteException e) {
3911 app.resetPackageList();
3912 startProcessLocked(app, "link fail", processName);
3913 return false;
3914 }
3915
Doug Zongker2bec3d42009-12-04 12:52:44 -08003916 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917
3918 app.thread = thread;
3919 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003920 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3921 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 app.forcingToForeground = null;
3923 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003924 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 app.debugging = false;
3926
3927 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3928
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003929 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003930 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003932 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003933 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003934 }
3935
Joe Onorato8a9b2202010-02-26 18:56:32 -08003936 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 TAG, "New app record " + app
3938 + " thread=" + thread.asBinder() + " pid=" + pid);
3939 try {
3940 int testMode = IApplicationThread.DEBUG_OFF;
3941 if (mDebugApp != null && mDebugApp.equals(processName)) {
3942 testMode = mWaitForDebugger
3943 ? IApplicationThread.DEBUG_WAIT
3944 : IApplicationThread.DEBUG_ON;
3945 app.debugging = true;
3946 if (mDebugTransient) {
3947 mDebugApp = mOrigDebugApp;
3948 mWaitForDebugger = mOrigWaitForDebugger;
3949 }
3950 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003951 String profileFile = app.instrumentationProfileFile;
3952 ParcelFileDescriptor profileFd = null;
3953 boolean profileAutoStop = false;
3954 if (mProfileApp != null && mProfileApp.equals(processName)) {
3955 mProfileProc = app;
3956 profileFile = mProfileFile;
3957 profileFd = mProfileFd;
3958 profileAutoStop = mAutoStopProfiler;
3959 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003960 boolean enableOpenGlTrace = false;
3961 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3962 enableOpenGlTrace = true;
3963 mOpenGlTraceApp = null;
3964 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003965
Christopher Tate181fafa2009-05-14 11:12:14 -07003966 // If the app is being launched for restore or full backup, set it up specially
3967 boolean isRestrictedBackupMode = false;
3968 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3969 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003970 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003971 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3972 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003973
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003974 ensurePackageDexOpt(app.instrumentationInfo != null
3975 ? app.instrumentationInfo.packageName
3976 : app.info.packageName);
3977 if (app.instrumentationClass != null) {
3978 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003979 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003980 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003981 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003982 ApplicationInfo appInfo = app.instrumentationInfo != null
3983 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003984 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003985 if (profileFd != null) {
3986 profileFd = profileFd.dup();
3987 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003988 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003989 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003990 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3991 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003992 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003993 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003994 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003995 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 } catch (Exception e) {
3997 // todo: Yikes! What should we do? For now we will try to
3998 // start another process, but that could easily get us in
3999 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004000 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001
4002 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004003 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 startProcessLocked(app, "bind fail", processName);
4005 return false;
4006 }
4007
4008 // Remove this record from the list of starting applications.
4009 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004010 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4011 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 mProcessesOnHold.remove(app);
4013
4014 boolean badApp = false;
4015 boolean didSomething = false;
4016
4017 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004018 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004019 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004020 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 && processName.equals(hr.processName)) {
4022 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004023 if (mHeadless) {
4024 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4025 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 didSomething = true;
4027 }
4028 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004029 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 + hr.intent.getComponent().flattenToShortString(), e);
4031 badApp = true;
4032 }
4033 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004034 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 }
4036 }
4037
4038 // Find any services that should be running in this process...
4039 if (!badApp && mPendingServices.size() > 0) {
4040 ServiceRecord sr = null;
4041 try {
4042 for (int i=0; i<mPendingServices.size(); i++) {
4043 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004044 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4045 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 continue;
4047 }
4048
4049 mPendingServices.remove(i);
4050 i--;
4051 realStartServiceLocked(sr, app);
4052 didSomething = true;
4053 }
4054 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004055 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 + sr.shortName, e);
4057 badApp = true;
4058 }
4059 }
4060
Christopher Tatef46723b2012-01-26 14:19:24 -08004061 // Check if a next-broadcast receiver is in this process...
4062 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004064 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004066 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 }
4069 }
4070
Christopher Tate181fafa2009-05-14 11:12:14 -07004071 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004072 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004073 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004074 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004075 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004076 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4077 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4078 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004079 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004080 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004081 e.printStackTrace();
4082 }
4083 }
4084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 if (badApp) {
4086 // todo: Also need to kill application to deal with all
4087 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004088 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 return false;
4090 }
4091
4092 if (!didSomething) {
4093 updateOomAdjLocked();
4094 }
4095
4096 return true;
4097 }
4098
4099 public final void attachApplication(IApplicationThread thread) {
4100 synchronized (this) {
4101 int callingPid = Binder.getCallingPid();
4102 final long origId = Binder.clearCallingIdentity();
4103 attachApplicationLocked(thread, callingPid);
4104 Binder.restoreCallingIdentity(origId);
4105 }
4106 }
4107
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004108 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004110 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4111 if (stopProfiling) {
4112 synchronized (this) {
4113 if (mProfileProc == r.app) {
4114 if (mProfileFd != null) {
4115 try {
4116 mProfileFd.close();
4117 } catch (IOException e) {
4118 }
4119 clearProfilerLocked();
4120 }
4121 }
4122 }
4123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 Binder.restoreCallingIdentity(origId);
4125 }
4126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004128 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004129 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004131
4132 synchronized (this) {
4133 updateEventDispatchingLocked();
4134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 }
4136
Dianne Hackborn661cd522011-08-22 00:26:20 -07004137 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004138 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004139 mWindowManager.showBootMessage(msg, always);
4140 }
4141
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004142 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004143 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004144 final long token = Binder.clearCallingIdentity();
4145 try {
4146 synchronized (this) {
4147 if (mLockScreenShown) {
4148 mLockScreenShown = false;
4149 comeOutOfSleepIfNeededLocked();
4150 }
4151 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004152 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004153 } finally {
4154 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004155 }
4156 }
4157
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004158 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004159 IntentFilter pkgFilter = new IntentFilter();
4160 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4161 pkgFilter.addDataScheme("package");
4162 mContext.registerReceiver(new BroadcastReceiver() {
4163 @Override
4164 public void onReceive(Context context, Intent intent) {
4165 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4166 if (pkgs != null) {
4167 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004168 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004169 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4170 setResultCode(Activity.RESULT_OK);
4171 return;
4172 }
4173 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004174 }
4175 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004176 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004177 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004178
4179 IntentFilter userFilter = new IntentFilter();
4180 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4181 mContext.registerReceiver(new BroadcastReceiver() {
4182 @Override
4183 public void onReceive(Context context, Intent intent) {
4184 onUserRemoved(intent);
4185 }
4186 }, userFilter);
4187
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004188 synchronized (this) {
4189 // Ensure that any processes we had put on hold are now started
4190 // up.
4191 final int NP = mProcessesOnHold.size();
4192 if (NP > 0) {
4193 ArrayList<ProcessRecord> procs =
4194 new ArrayList<ProcessRecord>(mProcessesOnHold);
4195 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004196 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4197 + procs.get(ip));
4198 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004199 }
4200 }
4201
4202 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004203 // Start looking for apps that are abusing wake locks.
4204 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004205 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004206 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004207 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004208 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004209 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004210 broadcastIntentLocked(null, null,
4211 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4212 null, null, 0, null, null,
4213 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004214 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004215 }
4216 }
4217 }
4218
4219 final void ensureBootCompleted() {
4220 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004221 boolean enableScreen;
4222 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004223 booting = mBooting;
4224 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004225 enableScreen = !mBooted;
4226 mBooted = true;
4227 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004228
4229 if (booting) {
4230 finishBooting();
4231 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004232
4233 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004234 enableScreenAfterBoot();
4235 }
4236 }
4237
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004238 public final void activityPaused(IBinder token) {
4239 final long origId = Binder.clearCallingIdentity();
4240 mMainStack.activityPaused(token, false);
4241 Binder.restoreCallingIdentity(origId);
4242 }
4243
4244 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4245 CharSequence description) {
4246 if (localLOGV) Slog.v(
4247 TAG, "Activity stopped: token=" + token);
4248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 // Refuse possible leaked file descriptors
4250 if (icicle != null && icicle.hasFileDescriptors()) {
4251 throw new IllegalArgumentException("File descriptors passed in Bundle");
4252 }
4253
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004254 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255
4256 final long origId = Binder.clearCallingIdentity();
4257
4258 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004259 r = mMainStack.isInStackLocked(token);
4260 if (r != null) {
4261 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 }
4263 }
4264
4265 if (r != null) {
4266 sendPendingThumbnail(r, null, null, null, false);
4267 }
4268
4269 trimApplications();
4270
4271 Binder.restoreCallingIdentity(origId);
4272 }
4273
4274 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004275 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004276 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 }
4278
4279 public String getCallingPackage(IBinder token) {
4280 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004281 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004282 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
4284 }
4285
4286 public ComponentName getCallingActivity(IBinder token) {
4287 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004288 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 return r != null ? r.intent.getComponent() : null;
4290 }
4291 }
4292
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004293 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004294 ActivityRecord r = mMainStack.isInStackLocked(token);
4295 if (r == null) {
4296 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004298 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 }
4300
4301 public ComponentName getActivityClassForToken(IBinder token) {
4302 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004303 ActivityRecord r = mMainStack.isInStackLocked(token);
4304 if (r == null) {
4305 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004307 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 }
4309 }
4310
4311 public String getPackageForToken(IBinder token) {
4312 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004313 ActivityRecord r = mMainStack.isInStackLocked(token);
4314 if (r == null) {
4315 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004317 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
4319 }
4320
4321 public IIntentSender getIntentSender(int type,
4322 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004323 int requestCode, Intent[] intents, String[] resolvedTypes,
4324 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004325 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004327 if (intents != null) {
4328 if (intents.length < 1) {
4329 throw new IllegalArgumentException("Intents array length must be >= 1");
4330 }
4331 for (int i=0; i<intents.length; i++) {
4332 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004333 if (intent != null) {
4334 if (intent.hasFileDescriptors()) {
4335 throw new IllegalArgumentException("File descriptors passed in Intent");
4336 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004337 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004338 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4339 throw new IllegalArgumentException(
4340 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4341 }
4342 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004343 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004344 }
4345 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004346 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004347 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004348 }
4349 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004350 if (options != null) {
4351 if (options.hasFileDescriptors()) {
4352 throw new IllegalArgumentException("File descriptors passed in options");
4353 }
4354 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 synchronized(this) {
4357 int callingUid = Binder.getCallingUid();
4358 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004359 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004360 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004361 .getPackageUid(packageName, UserId.getUserId(callingUid));
4362 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 String msg = "Permission Denial: getIntentSender() from pid="
4364 + Binder.getCallingPid()
4365 + ", uid=" + Binder.getCallingUid()
4366 + ", (need uid=" + uid + ")"
4367 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004368 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 throw new SecurityException(msg);
4370 }
4371 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004372
Amith Yamasani742a6712011-05-04 14:49:28 -07004373 if (DEBUG_MU)
4374 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4375 + Binder.getOrigCallingUid());
4376 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004377 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 } catch (RemoteException e) {
4380 throw new SecurityException(e);
4381 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004382 }
4383 }
4384
4385 IIntentSender getIntentSenderLocked(int type,
4386 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004387 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4388 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004389 if (DEBUG_MU)
4390 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004391 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004392 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004393 activity = mMainStack.isInStackLocked(token);
4394 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004395 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004397 if (activity.finishing) {
4398 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004400 }
4401
4402 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4403 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4404 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4405 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4406 |PendingIntent.FLAG_UPDATE_CURRENT);
4407
4408 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4409 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004410 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004411 WeakReference<PendingIntentRecord> ref;
4412 ref = mIntentSenderRecords.get(key);
4413 PendingIntentRecord rec = ref != null ? ref.get() : null;
4414 if (rec != null) {
4415 if (!cancelCurrent) {
4416 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004417 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004418 rec.key.requestIntent.replaceExtras(intents != null ?
4419 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004420 }
4421 if (intents != null) {
4422 intents[intents.length-1] = rec.key.requestIntent;
4423 rec.key.allIntents = intents;
4424 rec.key.allResolvedTypes = resolvedTypes;
4425 } else {
4426 rec.key.allIntents = null;
4427 rec.key.allResolvedTypes = null;
4428 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 return rec;
4431 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004432 rec.canceled = true;
4433 mIntentSenderRecords.remove(key);
4434 }
4435 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004436 return rec;
4437 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004438 rec = new PendingIntentRecord(this, key, callingUid);
4439 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004440 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004441 if (activity.pendingResults == null) {
4442 activity.pendingResults
4443 = new HashSet<WeakReference<PendingIntentRecord>>();
4444 }
4445 activity.pendingResults.add(rec.ref);
4446 }
4447 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 }
4449
4450 public void cancelIntentSender(IIntentSender sender) {
4451 if (!(sender instanceof PendingIntentRecord)) {
4452 return;
4453 }
4454 synchronized(this) {
4455 PendingIntentRecord rec = (PendingIntentRecord)sender;
4456 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004457 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004458 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004459 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 String msg = "Permission Denial: cancelIntentSender() from pid="
4461 + Binder.getCallingPid()
4462 + ", uid=" + Binder.getCallingUid()
4463 + " is not allowed to cancel packges "
4464 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004465 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 throw new SecurityException(msg);
4467 }
4468 } catch (RemoteException e) {
4469 throw new SecurityException(e);
4470 }
4471 cancelIntentSenderLocked(rec, true);
4472 }
4473 }
4474
4475 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4476 rec.canceled = true;
4477 mIntentSenderRecords.remove(rec.key);
4478 if (cleanActivity && rec.key.activity != null) {
4479 rec.key.activity.pendingResults.remove(rec.ref);
4480 }
4481 }
4482
4483 public String getPackageForIntentSender(IIntentSender pendingResult) {
4484 if (!(pendingResult instanceof PendingIntentRecord)) {
4485 return null;
4486 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004487 try {
4488 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4489 return res.key.packageName;
4490 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 }
4492 return null;
4493 }
4494
Christopher Tatec4a07d12012-04-06 14:19:13 -07004495 public int getUidForIntentSender(IIntentSender sender) {
4496 if (sender instanceof PendingIntentRecord) {
4497 try {
4498 PendingIntentRecord res = (PendingIntentRecord)sender;
4499 return res.uid;
4500 } catch (ClassCastException e) {
4501 }
4502 }
4503 return -1;
4504 }
4505
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004506 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4507 if (!(pendingResult instanceof PendingIntentRecord)) {
4508 return false;
4509 }
4510 try {
4511 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4512 if (res.key.allIntents == null) {
4513 return false;
4514 }
4515 for (int i=0; i<res.key.allIntents.length; i++) {
4516 Intent intent = res.key.allIntents[i];
4517 if (intent.getPackage() != null && intent.getComponent() != null) {
4518 return false;
4519 }
4520 }
4521 return true;
4522 } catch (ClassCastException e) {
4523 }
4524 return false;
4525 }
4526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 public void setProcessLimit(int max) {
4528 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4529 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004530 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004531 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004532 mProcessLimitOverride = max;
4533 }
4534 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 }
4536
4537 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004538 synchronized (this) {
4539 return mProcessLimitOverride;
4540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 }
4542
4543 void foregroundTokenDied(ForegroundToken token) {
4544 synchronized (ActivityManagerService.this) {
4545 synchronized (mPidsSelfLocked) {
4546 ForegroundToken cur
4547 = mForegroundProcesses.get(token.pid);
4548 if (cur != token) {
4549 return;
4550 }
4551 mForegroundProcesses.remove(token.pid);
4552 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4553 if (pr == null) {
4554 return;
4555 }
4556 pr.forcingToForeground = null;
4557 pr.foregroundServices = false;
4558 }
4559 updateOomAdjLocked();
4560 }
4561 }
4562
4563 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4564 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4565 "setProcessForeground()");
4566 synchronized(this) {
4567 boolean changed = false;
4568
4569 synchronized (mPidsSelfLocked) {
4570 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004571 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004572 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 return;
4574 }
4575 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4576 if (oldToken != null) {
4577 oldToken.token.unlinkToDeath(oldToken, 0);
4578 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004579 if (pr != null) {
4580 pr.forcingToForeground = null;
4581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 changed = true;
4583 }
4584 if (isForeground && token != null) {
4585 ForegroundToken newToken = new ForegroundToken() {
4586 public void binderDied() {
4587 foregroundTokenDied(this);
4588 }
4589 };
4590 newToken.pid = pid;
4591 newToken.token = token;
4592 try {
4593 token.linkToDeath(newToken, 0);
4594 mForegroundProcesses.put(pid, newToken);
4595 pr.forcingToForeground = token;
4596 changed = true;
4597 } catch (RemoteException e) {
4598 // If the process died while doing this, we will later
4599 // do the cleanup with the process death link.
4600 }
4601 }
4602 }
4603
4604 if (changed) {
4605 updateOomAdjLocked();
4606 }
4607 }
4608 }
4609
4610 // =========================================================
4611 // PERMISSIONS
4612 // =========================================================
4613
4614 static class PermissionController extends IPermissionController.Stub {
4615 ActivityManagerService mActivityManagerService;
4616 PermissionController(ActivityManagerService activityManagerService) {
4617 mActivityManagerService = activityManagerService;
4618 }
4619
4620 public boolean checkPermission(String permission, int pid, int uid) {
4621 return mActivityManagerService.checkPermission(permission, pid,
4622 uid) == PackageManager.PERMISSION_GRANTED;
4623 }
4624 }
4625
4626 /**
4627 * This can be called with or without the global lock held.
4628 */
4629 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004630 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 // We might be performing an operation on behalf of an indirect binder
4632 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4633 // client identity accordingly before proceeding.
4634 Identity tlsIdentity = sCallerIdentity.get();
4635 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004636 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4638 uid = tlsIdentity.uid;
4639 pid = tlsIdentity.pid;
4640 }
4641
4642 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004643 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 return PackageManager.PERMISSION_GRANTED;
4645 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004646 // Isolated processes don't get any permissions.
4647 if (UserId.isIsolated(uid)) {
4648 return PackageManager.PERMISSION_DENIED;
4649 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004650 // If there is a uid that owns whatever is being accessed, it has
4651 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004652 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004653 return PackageManager.PERMISSION_GRANTED;
4654 }
4655 // If the target is not exported, then nobody else can get to it.
4656 if (!exported) {
4657 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004658 return PackageManager.PERMISSION_DENIED;
4659 }
4660 if (permission == null) {
4661 return PackageManager.PERMISSION_GRANTED;
4662 }
4663 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004664 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 .checkUidPermission(permission, uid);
4666 } catch (RemoteException e) {
4667 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004668 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 }
4670 return PackageManager.PERMISSION_DENIED;
4671 }
4672
4673 /**
4674 * As the only public entry point for permissions checking, this method
4675 * can enforce the semantic that requesting a check on a null global
4676 * permission is automatically denied. (Internally a null permission
4677 * string is used when calling {@link #checkComponentPermission} in cases
4678 * when only uid-based security is needed.)
4679 *
4680 * This can be called with or without the global lock held.
4681 */
4682 public int checkPermission(String permission, int pid, int uid) {
4683 if (permission == null) {
4684 return PackageManager.PERMISSION_DENIED;
4685 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004686 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 }
4688
4689 /**
4690 * Binder IPC calls go through the public entry point.
4691 * This can be called with or without the global lock held.
4692 */
4693 int checkCallingPermission(String permission) {
4694 return checkPermission(permission,
4695 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004696 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 }
4698
4699 /**
4700 * This can be called with or without the global lock held.
4701 */
4702 void enforceCallingPermission(String permission, String func) {
4703 if (checkCallingPermission(permission)
4704 == PackageManager.PERMISSION_GRANTED) {
4705 return;
4706 }
4707
4708 String msg = "Permission Denial: " + func + " from pid="
4709 + Binder.getCallingPid()
4710 + ", uid=" + Binder.getCallingUid()
4711 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004712 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 throw new SecurityException(msg);
4714 }
4715
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004716 /**
4717 * Determine if UID is holding permissions required to access {@link Uri} in
4718 * the given {@link ProviderInfo}. Final permission checking is always done
4719 * in {@link ContentProvider}.
4720 */
4721 private final boolean checkHoldingPermissionsLocked(
4722 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004723 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4724 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004725
4726 if (pi.applicationInfo.uid == uid) {
4727 return true;
4728 } else if (!pi.exported) {
4729 return false;
4730 }
4731
4732 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4733 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004735 // check if target holds top-level <provider> permissions
4736 if (!readMet && pi.readPermission != null
4737 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4738 readMet = true;
4739 }
4740 if (!writeMet && pi.writePermission != null
4741 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4742 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004744
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004745 // track if unprotected read/write is allowed; any denied
4746 // <path-permission> below removes this ability
4747 boolean allowDefaultRead = pi.readPermission == null;
4748 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004749
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004750 // check if target holds any <path-permission> that match uri
4751 final PathPermission[] pps = pi.pathPermissions;
4752 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004753 final String path = uri.getPath();
4754 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004755 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004756 i--;
4757 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004758 if (pp.match(path)) {
4759 if (!readMet) {
4760 final String pprperm = pp.getReadPermission();
4761 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4762 + pprperm + " for " + pp.getPath()
4763 + ": match=" + pp.match(path)
4764 + " check=" + pm.checkUidPermission(pprperm, uid));
4765 if (pprperm != null) {
4766 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4767 readMet = true;
4768 } else {
4769 allowDefaultRead = false;
4770 }
4771 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004772 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004773 if (!writeMet) {
4774 final String ppwperm = pp.getWritePermission();
4775 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4776 + ppwperm + " for " + pp.getPath()
4777 + ": match=" + pp.match(path)
4778 + " check=" + pm.checkUidPermission(ppwperm, uid));
4779 if (ppwperm != null) {
4780 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4781 writeMet = true;
4782 } else {
4783 allowDefaultWrite = false;
4784 }
4785 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004786 }
4787 }
4788 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004789 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004790
4791 // grant unprotected <provider> read/write, if not blocked by
4792 // <path-permission> above
4793 if (allowDefaultRead) readMet = true;
4794 if (allowDefaultWrite) writeMet = true;
4795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 } catch (RemoteException e) {
4797 return false;
4798 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004799
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004800 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004801 }
4802
4803 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4804 int modeFlags) {
4805 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004806 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 return true;
4808 }
4809 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4810 if (perms == null) return false;
4811 UriPermission perm = perms.get(uri);
4812 if (perm == null) return false;
4813 return (modeFlags&perm.modeFlags) == modeFlags;
4814 }
4815
4816 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004817 enforceNotIsolatedCaller("checkUriPermission");
4818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 // Another redirected-binder-call permissions check as in
4820 // {@link checkComponentPermission}.
4821 Identity tlsIdentity = sCallerIdentity.get();
4822 if (tlsIdentity != null) {
4823 uid = tlsIdentity.uid;
4824 pid = tlsIdentity.pid;
4825 }
4826
Amith Yamasani742a6712011-05-04 14:49:28 -07004827 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828 // Our own process gets to do everything.
4829 if (pid == MY_PID) {
4830 return PackageManager.PERMISSION_GRANTED;
4831 }
4832 synchronized(this) {
4833 return checkUriPermissionLocked(uri, uid, modeFlags)
4834 ? PackageManager.PERMISSION_GRANTED
4835 : PackageManager.PERMISSION_DENIED;
4836 }
4837 }
4838
Dianne Hackborn39792d22010-08-19 18:01:52 -07004839 /**
4840 * Check if the targetPkg can be granted permission to access uri by
4841 * the callingUid using the given modeFlags. Throws a security exception
4842 * if callingUid is not allowed to do this. Returns the uid of the target
4843 * if the URI permission grant should be performed; returns -1 if it is not
4844 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004845 * If you already know the uid of the target, you can supply it in
4846 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004847 */
4848 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004849 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4851 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4852 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004853 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 }
4855
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004856 if (targetPkg != null) {
4857 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4858 "Checking grant " + targetPkg + " permission to " + uri);
4859 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004860
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004861 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004862
4863 // If this is not a content: uri, we can't do anything with it.
4864 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004865 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004866 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004867 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 }
4869
4870 String name = uri.getAuthority();
4871 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004872 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4873 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004874 if (cpr != null) {
4875 pi = cpr.info;
4876 } else {
4877 try {
4878 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004879 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 } catch (RemoteException ex) {
4881 }
4882 }
4883 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004884 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004885 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004886 }
4887
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004888 int targetUid = lastTargetUid;
4889 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004890 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004891 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004892 if (targetUid < 0) {
4893 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4894 "Can't grant URI permission no uid for: " + targetPkg);
4895 return -1;
4896 }
4897 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004898 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 }
4901
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004902 if (targetUid >= 0) {
4903 // First... does the target actually need this permission?
4904 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4905 // No need to grant the target this permission.
4906 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4907 "Target " + targetPkg + " already has full permission to " + uri);
4908 return -1;
4909 }
4910 } else {
4911 // First... there is no target package, so can anyone access it?
4912 boolean allowed = pi.exported;
4913 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4914 if (pi.readPermission != null) {
4915 allowed = false;
4916 }
4917 }
4918 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4919 if (pi.writePermission != null) {
4920 allowed = false;
4921 }
4922 }
4923 if (allowed) {
4924 return -1;
4925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 }
4927
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004928 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 if (!pi.grantUriPermissions) {
4930 throw new SecurityException("Provider " + pi.packageName
4931 + "/" + pi.name
4932 + " does not allow granting of Uri permissions (uri "
4933 + uri + ")");
4934 }
4935 if (pi.uriPermissionPatterns != null) {
4936 final int N = pi.uriPermissionPatterns.length;
4937 boolean allowed = false;
4938 for (int i=0; i<N; i++) {
4939 if (pi.uriPermissionPatterns[i] != null
4940 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4941 allowed = true;
4942 break;
4943 }
4944 }
4945 if (!allowed) {
4946 throw new SecurityException("Provider " + pi.packageName
4947 + "/" + pi.name
4948 + " does not allow granting of permission to path of Uri "
4949 + uri);
4950 }
4951 }
4952
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004953 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004955 if (callingUid != Process.myUid()) {
4956 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4957 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4958 throw new SecurityException("Uid " + callingUid
4959 + " does not have permission to uri " + uri);
4960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004961 }
4962 }
4963
Dianne Hackborn39792d22010-08-19 18:01:52 -07004964 return targetUid;
4965 }
4966
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004967 public int checkGrantUriPermission(int callingUid, String targetPkg,
4968 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004969 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004970 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004971 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004972 }
4973 }
4974
Dianne Hackborn39792d22010-08-19 18:01:52 -07004975 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4976 Uri uri, int modeFlags, UriPermissionOwner owner) {
4977 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4978 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4979 if (modeFlags == 0) {
4980 return;
4981 }
4982
4983 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 // to the uri, and the target doesn't. Let's now give this to
4985 // the target.
4986
Joe Onorato8a9b2202010-02-26 18:56:32 -08004987 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004988 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 HashMap<Uri, UriPermission> targetUris
4991 = mGrantedUriPermissions.get(targetUid);
4992 if (targetUris == null) {
4993 targetUris = new HashMap<Uri, UriPermission>();
4994 mGrantedUriPermissions.put(targetUid, targetUris);
4995 }
4996
4997 UriPermission perm = targetUris.get(uri);
4998 if (perm == null) {
4999 perm = new UriPermission(targetUid, uri);
5000 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005003 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005004 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005006 } else {
5007 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5008 perm.readOwners.add(owner);
5009 owner.addReadPermission(perm);
5010 }
5011 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5012 perm.writeOwners.add(owner);
5013 owner.addWritePermission(perm);
5014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 }
5016 }
5017
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005018 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5019 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005020 if (targetPkg == null) {
5021 throw new NullPointerException("targetPkg");
5022 }
5023
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005024 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005025 if (targetUid < 0) {
5026 return;
5027 }
5028
5029 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5030 }
5031
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005032 static class NeededUriGrants extends ArrayList<Uri> {
5033 final String targetPkg;
5034 final int targetUid;
5035 final int flags;
5036
5037 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5038 targetPkg = _targetPkg;
5039 targetUid = _targetUid;
5040 flags = _flags;
5041 }
5042 }
5043
Dianne Hackborn39792d22010-08-19 18:01:52 -07005044 /**
5045 * Like checkGrantUriPermissionLocked, but takes an Intent.
5046 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005047 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5048 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005049 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005050 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5051 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005052 + " from " + intent + "; flags=0x"
5053 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5054
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005055 if (targetPkg == null) {
5056 throw new NullPointerException("targetPkg");
5057 }
5058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005060 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 }
5062 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005063 ClipData clip = intent.getClipData();
5064 if (data == null && clip == null) {
5065 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005066 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005067 if (data != null) {
5068 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5069 mode, needed != null ? needed.targetUid : -1);
5070 if (target > 0) {
5071 if (needed == null) {
5072 needed = new NeededUriGrants(targetPkg, target, mode);
5073 }
5074 needed.add(data);
5075 }
5076 }
5077 if (clip != null) {
5078 for (int i=0; i<clip.getItemCount(); i++) {
5079 Uri uri = clip.getItemAt(i).getUri();
5080 if (uri != null) {
5081 int target = -1;
5082 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5083 mode, needed != null ? needed.targetUid : -1);
5084 if (target > 0) {
5085 if (needed == null) {
5086 needed = new NeededUriGrants(targetPkg, target, mode);
5087 }
5088 needed.add(uri);
5089 }
5090 } else {
5091 Intent clipIntent = clip.getItemAt(i).getIntent();
5092 if (clipIntent != null) {
5093 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5094 callingUid, targetPkg, clipIntent, mode, needed);
5095 if (newNeeded != null) {
5096 needed = newNeeded;
5097 }
5098 }
5099 }
5100 }
5101 }
5102
5103 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005104 }
5105
5106 /**
5107 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5108 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005109 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5110 UriPermissionOwner owner) {
5111 if (needed != null) {
5112 for (int i=0; i<needed.size(); i++) {
5113 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5114 needed.get(i), needed.flags, owner);
5115 }
5116 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005117 }
5118
5119 void grantUriPermissionFromIntentLocked(int callingUid,
5120 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005121 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005122 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005123 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 return;
5125 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005126
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005127 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 }
5129
5130 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5131 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005132 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 synchronized(this) {
5134 final ProcessRecord r = getRecordForAppLocked(caller);
5135 if (r == null) {
5136 throw new SecurityException("Unable to find app for caller "
5137 + caller
5138 + " when granting permission to uri " + uri);
5139 }
5140 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005141 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 }
5143 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005144 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 }
5146
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005147 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 null);
5149 }
5150 }
5151
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005152 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5154 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5155 HashMap<Uri, UriPermission> perms
5156 = mGrantedUriPermissions.get(perm.uid);
5157 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005158 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005159 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 perms.remove(perm.uri);
5161 if (perms.size() == 0) {
5162 mGrantedUriPermissions.remove(perm.uid);
5163 }
5164 }
5165 }
5166 }
5167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5169 int modeFlags) {
5170 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5171 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5172 if (modeFlags == 0) {
5173 return;
5174 }
5175
Joe Onorato8a9b2202010-02-26 18:56:32 -08005176 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005177 "Revoking all granted permissions to " + uri);
5178
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005179 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180
5181 final String authority = uri.getAuthority();
5182 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005183 int userId = UserId.getUserId(callingUid);
5184 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005185 if (cpr != null) {
5186 pi = cpr.info;
5187 } else {
5188 try {
5189 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005190 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 } catch (RemoteException ex) {
5192 }
5193 }
5194 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005195 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 return;
5197 }
5198
5199 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005200 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 // Right now, if you are not the original owner of the permission,
5202 // you are not allowed to revoke it.
5203 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5204 throw new SecurityException("Uid " + callingUid
5205 + " does not have permission to uri " + uri);
5206 //}
5207 }
5208
5209 // Go through all of the permissions and remove any that match.
5210 final List<String> SEGMENTS = uri.getPathSegments();
5211 if (SEGMENTS != null) {
5212 final int NS = SEGMENTS.size();
5213 int N = mGrantedUriPermissions.size();
5214 for (int i=0; i<N; i++) {
5215 HashMap<Uri, UriPermission> perms
5216 = mGrantedUriPermissions.valueAt(i);
5217 Iterator<UriPermission> it = perms.values().iterator();
5218 toploop:
5219 while (it.hasNext()) {
5220 UriPermission perm = it.next();
5221 Uri targetUri = perm.uri;
5222 if (!authority.equals(targetUri.getAuthority())) {
5223 continue;
5224 }
5225 List<String> targetSegments = targetUri.getPathSegments();
5226 if (targetSegments == null) {
5227 continue;
5228 }
5229 if (targetSegments.size() < NS) {
5230 continue;
5231 }
5232 for (int j=0; j<NS; j++) {
5233 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5234 continue toploop;
5235 }
5236 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005237 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005238 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005239 perm.clearModes(modeFlags);
5240 if (perm.modeFlags == 0) {
5241 it.remove();
5242 }
5243 }
5244 if (perms.size() == 0) {
5245 mGrantedUriPermissions.remove(
5246 mGrantedUriPermissions.keyAt(i));
5247 N--;
5248 i--;
5249 }
5250 }
5251 }
5252 }
5253
5254 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5255 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005256 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 synchronized(this) {
5258 final ProcessRecord r = getRecordForAppLocked(caller);
5259 if (r == null) {
5260 throw new SecurityException("Unable to find app for caller "
5261 + caller
5262 + " when revoking permission to uri " + uri);
5263 }
5264 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005265 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 return;
5267 }
5268
5269 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5270 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5271 if (modeFlags == 0) {
5272 return;
5273 }
5274
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005275 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276
5277 final String authority = uri.getAuthority();
5278 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005279 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 if (cpr != null) {
5281 pi = cpr.info;
5282 } else {
5283 try {
5284 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005285 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 } catch (RemoteException ex) {
5287 }
5288 }
5289 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005290 Slog.w(TAG, "No content provider found for permission revoke: "
5291 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292 return;
5293 }
5294
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005295 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296 }
5297 }
5298
Dianne Hackborn7e269642010-08-25 19:50:20 -07005299 @Override
5300 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005301 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005302 synchronized(this) {
5303 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5304 return owner.getExternalTokenLocked();
5305 }
5306 }
5307
5308 @Override
5309 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5310 Uri uri, int modeFlags) {
5311 synchronized(this) {
5312 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5313 if (owner == null) {
5314 throw new IllegalArgumentException("Unknown owner: " + token);
5315 }
5316 if (fromUid != Binder.getCallingUid()) {
5317 if (Binder.getCallingUid() != Process.myUid()) {
5318 // Only system code can grant URI permissions on behalf
5319 // of other users.
5320 throw new SecurityException("nice try");
5321 }
5322 }
5323 if (targetPkg == null) {
5324 throw new IllegalArgumentException("null target");
5325 }
5326 if (uri == null) {
5327 throw new IllegalArgumentException("null uri");
5328 }
5329
5330 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5331 }
5332 }
5333
5334 @Override
5335 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5336 synchronized(this) {
5337 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5338 if (owner == null) {
5339 throw new IllegalArgumentException("Unknown owner: " + token);
5340 }
5341
5342 if (uri == null) {
5343 owner.removeUriPermissionsLocked(mode);
5344 } else {
5345 owner.removeUriPermissionLocked(uri, mode);
5346 }
5347 }
5348 }
5349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5351 synchronized (this) {
5352 ProcessRecord app =
5353 who != null ? getRecordForAppLocked(who) : null;
5354 if (app == null) return;
5355
5356 Message msg = Message.obtain();
5357 msg.what = WAIT_FOR_DEBUGGER_MSG;
5358 msg.obj = app;
5359 msg.arg1 = waiting ? 1 : 0;
5360 mHandler.sendMessage(msg);
5361 }
5362 }
5363
5364 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005365 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5366 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005368 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005369 outInfo.threshold = homeAppMem;
5370 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5371 outInfo.hiddenAppThreshold = hiddenAppMem;
5372 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005373 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005374 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5375 ProcessList.VISIBLE_APP_ADJ);
5376 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5377 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 }
5379
5380 // =========================================================
5381 // TASK MANAGEMENT
5382 // =========================================================
5383
5384 public List getTasks(int maxNum, int flags,
5385 IThumbnailReceiver receiver) {
5386 ArrayList list = new ArrayList();
5387
5388 PendingThumbnailsRecord pending = null;
5389 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005390 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391
5392 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005393 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5395 + ", receiver=" + receiver);
5396
5397 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5398 != PackageManager.PERMISSION_GRANTED) {
5399 if (receiver != null) {
5400 // If the caller wants to wait for pending thumbnails,
5401 // it ain't gonna get them.
5402 try {
5403 receiver.finished();
5404 } catch (RemoteException ex) {
5405 }
5406 }
5407 String msg = "Permission Denial: getTasks() from pid="
5408 + Binder.getCallingPid()
5409 + ", uid=" + Binder.getCallingUid()
5410 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005411 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 throw new SecurityException(msg);
5413 }
5414
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005415 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005416 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005417 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005418 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 TaskRecord curTask = null;
5420 int numActivities = 0;
5421 int numRunning = 0;
5422 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005423 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005425 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426
5427 // Initialize state for next task if needed.
5428 if (top == null ||
5429 (top.state == ActivityState.INITIALIZING
5430 && top.task == r.task)) {
5431 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 curTask = r.task;
5433 numActivities = numRunning = 0;
5434 }
5435
5436 // Add 'r' into the current task.
5437 numActivities++;
5438 if (r.app != null && r.app.thread != null) {
5439 numRunning++;
5440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441
Joe Onorato8a9b2202010-02-26 18:56:32 -08005442 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 TAG, r.intent.getComponent().flattenToShortString()
5444 + ": task=" + r.task);
5445
5446 // If the next one is a different task, generate a new
5447 // TaskInfo entry for what we have.
5448 if (next == null || next.task != curTask) {
5449 ActivityManager.RunningTaskInfo ci
5450 = new ActivityManager.RunningTaskInfo();
5451 ci.id = curTask.taskId;
5452 ci.baseActivity = r.intent.getComponent();
5453 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005454 if (top.thumbHolder != null) {
5455 ci.description = top.thumbHolder.lastDescription;
5456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 ci.numActivities = numActivities;
5458 ci.numRunning = numRunning;
5459 //System.out.println(
5460 // "#" + maxNum + ": " + " descr=" + ci.description);
5461 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005462 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 TAG, "State=" + top.state + "Idle=" + top.idle
5464 + " app=" + top.app
5465 + " thr=" + (top.app != null ? top.app.thread : null));
5466 if (top.state == ActivityState.RESUMED
5467 || top.state == ActivityState.PAUSING) {
5468 if (top.idle && top.app != null
5469 && top.app.thread != null) {
5470 topRecord = top;
5471 topThumbnail = top.app.thread;
5472 } else {
5473 top.thumbnailNeeded = true;
5474 }
5475 }
5476 if (pending == null) {
5477 pending = new PendingThumbnailsRecord(receiver);
5478 }
5479 pending.pendingRecords.add(top);
5480 }
5481 list.add(ci);
5482 maxNum--;
5483 top = null;
5484 }
5485 }
5486
5487 if (pending != null) {
5488 mPendingThumbnails.add(pending);
5489 }
5490 }
5491
Joe Onorato8a9b2202010-02-26 18:56:32 -08005492 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493
5494 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005495 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005497 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005499 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005500 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 }
5502 }
5503
5504 if (pending == null && receiver != null) {
5505 // In this case all thumbnails were available and the client
5506 // is being asked to be told when the remaining ones come in...
5507 // which is unusually, since the top-most currently running
5508 // activity should never have a canned thumbnail! Oh well.
5509 try {
5510 receiver.finished();
5511 } catch (RemoteException ex) {
5512 }
5513 }
5514
5515 return list;
5516 }
5517
5518 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5519 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005520 final int callingUid = Binder.getCallingUid();
5521 // If it's the system uid asking, then use the current user id.
5522 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5523 // require the entire list.
5524 final int callingUserId = callingUid == Process.SYSTEM_UID
5525 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 synchronized (this) {
5527 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5528 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005529 final boolean detailed = checkCallingPermission(
5530 android.Manifest.permission.GET_DETAILED_TASKS)
5531 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005533 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 final int N = mRecentTasks.size();
5536 ArrayList<ActivityManager.RecentTaskInfo> res
5537 = new ArrayList<ActivityManager.RecentTaskInfo>(
5538 maxNum < N ? maxNum : N);
5539 for (int i=0; i<N && maxNum > 0; i++) {
5540 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005541 // Only add calling user's recent tasks
5542 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005543 // Return the entry if desired by the caller. We always return
5544 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005545 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005546 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5547 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005548
Dianne Hackborn905577f2011-09-07 18:31:28 -07005549 if (i == 0
5550 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 || (tr.intent == null)
5552 || ((tr.intent.getFlags()
5553 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5554 ActivityManager.RecentTaskInfo rti
5555 = new ActivityManager.RecentTaskInfo();
5556 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005557 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 rti.baseIntent = new Intent(
5559 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005560 if (!detailed) {
5561 rti.baseIntent.replaceExtras((Bundle)null);
5562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005564 rti.description = tr.lastDescription;
5565
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005566 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5567 // Check whether this activity is currently available.
5568 try {
5569 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005570 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5571 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005572 continue;
5573 }
5574 } else if (rti.baseIntent != null) {
5575 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005576 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005577 continue;
5578 }
5579 }
5580 } catch (RemoteException e) {
5581 // Will never happen.
5582 }
5583 }
5584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 res.add(rti);
5586 maxNum--;
5587 }
5588 }
5589 return res;
5590 }
5591 }
5592
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005593 private TaskRecord taskForIdLocked(int id) {
5594 final int N = mRecentTasks.size();
5595 for (int i=0; i<N; i++) {
5596 TaskRecord tr = mRecentTasks.get(i);
5597 if (tr.taskId == id) {
5598 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005599 }
5600 }
5601 return null;
5602 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005603
5604 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5605 synchronized (this) {
5606 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5607 "getTaskThumbnails()");
5608 TaskRecord tr = taskForIdLocked(id);
5609 if (tr != null) {
5610 return mMainStack.getTaskThumbnailsLocked(tr);
5611 }
5612 }
5613 return null;
5614 }
5615
5616 public boolean removeSubTask(int taskId, int subTaskIndex) {
5617 synchronized (this) {
5618 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5619 "removeSubTask()");
5620 long ident = Binder.clearCallingIdentity();
5621 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005622 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5623 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005624 } finally {
5625 Binder.restoreCallingIdentity(ident);
5626 }
5627 }
5628 }
5629
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005630 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5631 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005632 Intent baseIntent = new Intent(
5633 tr.intent != null ? tr.intent : tr.affinityIntent);
5634 ComponentName component = baseIntent.getComponent();
5635 if (component == null) {
5636 Slog.w(TAG, "Now component for base intent of task: " + tr);
5637 return;
5638 }
5639
5640 // Find any running services associated with this app.
5641 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005642 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005643 if (sr.packageName.equals(component.getPackageName())) {
5644 services.add(sr);
5645 }
5646 }
5647
5648 // Take care of any running services associated with the app.
5649 for (int i=0; i<services.size(); i++) {
5650 ServiceRecord sr = services.get(i);
5651 if (sr.startRequested) {
5652 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005653 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005654 stopServiceLocked(sr);
5655 } else {
5656 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005657 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005658 if (sr.app != null && sr.app.thread != null) {
5659 sendServiceArgsLocked(sr, false);
5660 }
5661 }
5662 }
5663 }
5664
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005665 if (killProcesses) {
5666 // Find any running processes associated with this app.
5667 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5668 SparseArray<ProcessRecord> appProcs
5669 = mProcessNames.getMap().get(component.getPackageName());
5670 if (appProcs != null) {
5671 for (int i=0; i<appProcs.size(); i++) {
5672 procs.add(appProcs.valueAt(i));
5673 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005674 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005675
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005676 // Kill the running processes.
5677 for (int i=0; i<procs.size(); i++) {
5678 ProcessRecord pr = procs.get(i);
5679 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5680 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5681 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5682 pr.processName, pr.setAdj, "remove task");
5683 Process.killProcessQuiet(pr.pid);
5684 } else {
5685 pr.waitingToKill = "remove task";
5686 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005687 }
5688 }
5689 }
5690
5691 public boolean removeTask(int taskId, int flags) {
5692 synchronized (this) {
5693 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5694 "removeTask()");
5695 long ident = Binder.clearCallingIdentity();
5696 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005697 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5698 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005699 if (r != null) {
5700 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005701 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005702 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005703 } else {
5704 TaskRecord tr = null;
5705 int i=0;
5706 while (i < mRecentTasks.size()) {
5707 TaskRecord t = mRecentTasks.get(i);
5708 if (t.taskId == taskId) {
5709 tr = t;
5710 break;
5711 }
5712 i++;
5713 }
5714 if (tr != null) {
5715 if (tr.numActivities <= 0) {
5716 // Caller is just removing a recent task that is
5717 // not actively running. That is easy!
5718 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005719 cleanUpRemovedTaskLocked(tr, flags);
5720 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005721 } else {
5722 Slog.w(TAG, "removeTask: task " + taskId
5723 + " does not have activities to remove, "
5724 + " but numActivities=" + tr.numActivities
5725 + ": " + tr);
5726 }
5727 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005728 }
5729 } finally {
5730 Binder.restoreCallingIdentity(ident);
5731 }
5732 }
5733 return false;
5734 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5737 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005738 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 TaskRecord jt = startTask;
5740
5741 // First look backwards
5742 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005743 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 if (r.task != jt) {
5745 jt = r.task;
5746 if (affinity.equals(jt.affinity)) {
5747 return j;
5748 }
5749 }
5750 }
5751
5752 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005753 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 jt = startTask;
5755 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005756 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 if (r.task != jt) {
5758 if (affinity.equals(jt.affinity)) {
5759 return j;
5760 }
5761 jt = r.task;
5762 }
5763 }
5764
5765 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005766 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 return N-1;
5768 }
5769
5770 return -1;
5771 }
5772
5773 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005774 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005776 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5778 "moveTaskToFront()");
5779
5780 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005781 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5782 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005783 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005784 return;
5785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 final long origId = Binder.clearCallingIdentity();
5787 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005788 TaskRecord tr = taskForIdLocked(task);
5789 if (tr != null) {
5790 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5791 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005793 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5794 // Caller wants the home activity moved with it. To accomplish this,
5795 // we'll just move the home task to the top first.
5796 mMainStack.moveHomeToFrontLocked();
5797 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005798 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005799 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005801 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5802 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005804 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5805 mMainStack.mUserLeaving = true;
5806 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005807 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5808 // Caller wants the home activity moved with it. To accomplish this,
5809 // we'll just move the home task to the top first.
5810 mMainStack.moveHomeToFrontLocked();
5811 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005812 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 return;
5814 }
5815 }
5816 } finally {
5817 Binder.restoreCallingIdentity(origId);
5818 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005819 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 }
5821 }
5822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 public void moveTaskToBack(int task) {
5824 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5825 "moveTaskToBack()");
5826
5827 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005828 if (mMainStack.mResumedActivity != null
5829 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005830 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5831 Binder.getCallingUid(), "Task to back")) {
5832 return;
5833 }
5834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005836 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 Binder.restoreCallingIdentity(origId);
5838 }
5839 }
5840
5841 /**
5842 * Moves an activity, and all of the other activities within the same task, to the bottom
5843 * of the history stack. The activity's order within the task is unchanged.
5844 *
5845 * @param token A reference to the activity we wish to move
5846 * @param nonRoot If false then this only works if the activity is the root
5847 * of a task; if true it will work for any activity in a task.
5848 * @return Returns true if the move completed, false if not.
5849 */
5850 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005851 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 synchronized(this) {
5853 final long origId = Binder.clearCallingIdentity();
5854 int taskId = getTaskForActivityLocked(token, !nonRoot);
5855 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005856 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 }
5858 Binder.restoreCallingIdentity(origId);
5859 }
5860 return false;
5861 }
5862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 public void moveTaskBackwards(int task) {
5864 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5865 "moveTaskBackwards()");
5866
5867 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005868 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5869 Binder.getCallingUid(), "Task backwards")) {
5870 return;
5871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 final long origId = Binder.clearCallingIdentity();
5873 moveTaskBackwardsLocked(task);
5874 Binder.restoreCallingIdentity(origId);
5875 }
5876 }
5877
5878 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005879 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 }
5881
5882 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5883 synchronized(this) {
5884 return getTaskForActivityLocked(token, onlyRoot);
5885 }
5886 }
5887
5888 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005889 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 TaskRecord lastTask = null;
5891 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005892 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005893 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 if (!onlyRoot || lastTask != r.task) {
5895 return r.task.taskId;
5896 }
5897 return -1;
5898 }
5899 lastTask = r.task;
5900 }
5901
5902 return -1;
5903 }
5904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 // =========================================================
5906 // THUMBNAILS
5907 // =========================================================
5908
5909 public void reportThumbnail(IBinder token,
5910 Bitmap thumbnail, CharSequence description) {
5911 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5912 final long origId = Binder.clearCallingIdentity();
5913 sendPendingThumbnail(null, token, thumbnail, description, true);
5914 Binder.restoreCallingIdentity(origId);
5915 }
5916
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005917 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 Bitmap thumbnail, CharSequence description, boolean always) {
5919 TaskRecord task = null;
5920 ArrayList receivers = null;
5921
5922 //System.out.println("Send pending thumbnail: " + r);
5923
5924 synchronized(this) {
5925 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005926 r = mMainStack.isInStackLocked(token);
5927 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 return;
5929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005931 if (thumbnail == null && r.thumbHolder != null) {
5932 thumbnail = r.thumbHolder.lastThumbnail;
5933 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 }
5935 if (thumbnail == null && !always) {
5936 // If there is no thumbnail, and this entry is not actually
5937 // going away, then abort for now and pick up the next
5938 // thumbnail we get.
5939 return;
5940 }
5941 task = r.task;
5942
5943 int N = mPendingThumbnails.size();
5944 int i=0;
5945 while (i<N) {
5946 PendingThumbnailsRecord pr =
5947 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5948 //System.out.println("Looking in " + pr.pendingRecords);
5949 if (pr.pendingRecords.remove(r)) {
5950 if (receivers == null) {
5951 receivers = new ArrayList();
5952 }
5953 receivers.add(pr);
5954 if (pr.pendingRecords.size() == 0) {
5955 pr.finished = true;
5956 mPendingThumbnails.remove(i);
5957 N--;
5958 continue;
5959 }
5960 }
5961 i++;
5962 }
5963 }
5964
5965 if (receivers != null) {
5966 final int N = receivers.size();
5967 for (int i=0; i<N; i++) {
5968 try {
5969 PendingThumbnailsRecord pr =
5970 (PendingThumbnailsRecord)receivers.get(i);
5971 pr.receiver.newThumbnail(
5972 task != null ? task.taskId : -1, thumbnail, description);
5973 if (pr.finished) {
5974 pr.receiver.finished();
5975 }
5976 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005977 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 }
5979 }
5980 }
5981 }
5982
5983 // =========================================================
5984 // CONTENT PROVIDERS
5985 // =========================================================
5986
Jeff Brown10e89712011-07-08 18:52:57 -07005987 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5988 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005990 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005991 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005992 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 } catch (RemoteException ex) {
5994 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005995 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005996 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5997 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 if (providers != null) {
5999 final int N = providers.size();
6000 for (int i=0; i<N; i++) {
6001 ProviderInfo cpi =
6002 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006003
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006004 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006005 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006007 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006008 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006010 if (DEBUG_MU)
6011 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 app.pubProviders.put(cpi.name, cpr);
6013 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006014 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 }
6016 }
6017 return providers;
6018 }
6019
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006020 /**
6021 * Check if {@link ProcessRecord} has a possible chance at accessing the
6022 * given {@link ProviderInfo}. Final permission checking is always done
6023 * in {@link ContentProvider}.
6024 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006026 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006028 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006030 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006031 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 return null;
6033 }
6034 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006035 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 == PackageManager.PERMISSION_GRANTED) {
6037 return null;
6038 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006039
6040 PathPermission[] pps = cpi.pathPermissions;
6041 if (pps != null) {
6042 int i = pps.length;
6043 while (i > 0) {
6044 i--;
6045 PathPermission pp = pps[i];
6046 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006047 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006048 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006049 return null;
6050 }
6051 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006052 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006053 == PackageManager.PERMISSION_GRANTED) {
6054 return null;
6055 }
6056 }
6057 }
6058
Dianne Hackbornb424b632010-08-18 15:59:05 -07006059 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6060 if (perms != null) {
6061 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6062 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6063 return null;
6064 }
6065 }
6066 }
6067
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006068 String msg;
6069 if (!cpi.exported) {
6070 msg = "Permission Denial: opening provider " + cpi.name
6071 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6072 + ", uid=" + callingUid + ") that is not exported from uid "
6073 + cpi.applicationInfo.uid;
6074 } else {
6075 msg = "Permission Denial: opening provider " + cpi.name
6076 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6077 + ", uid=" + callingUid + ") requires "
6078 + cpi.readPermission + " or " + cpi.writePermission;
6079 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006080 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 return msg;
6082 }
6083
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006084 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6085 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006086 if (r != null) {
6087 Integer cnt = r.conProviders.get(cpr);
6088 if (DEBUG_PROVIDER) Slog.v(TAG,
6089 "Adding provider requested by "
6090 + r.processName + " from process "
6091 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6092 + " cnt=" + (cnt == null ? 1 : cnt));
6093 if (cnt == null) {
6094 cpr.clients.add(r);
6095 r.conProviders.put(cpr, new Integer(1));
6096 return true;
6097 } else {
6098 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6099 }
6100 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006101 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006102 }
6103 return false;
6104 }
6105
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006106 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6107 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006108 if (r != null) {
6109 Integer cnt = r.conProviders.get(cpr);
6110 if (DEBUG_PROVIDER) Slog.v(TAG,
6111 "Removing provider requested by "
6112 + r.processName + " from process "
6113 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6114 + " cnt=" + cnt);
6115 if (cnt == null || cnt.intValue() <= 1) {
6116 cpr.clients.remove(r);
6117 r.conProviders.remove(cpr);
6118 return true;
6119 } else {
6120 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6121 }
6122 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006123 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006124 }
6125 return false;
6126 }
6127
Amith Yamasani742a6712011-05-04 14:49:28 -07006128 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006129 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 ContentProviderRecord cpr;
6131 ProviderInfo cpi = null;
6132
6133 synchronized(this) {
6134 ProcessRecord r = null;
6135 if (caller != null) {
6136 r = getRecordForAppLocked(caller);
6137 if (r == null) {
6138 throw new SecurityException(
6139 "Unable to find app for caller " + caller
6140 + " (pid=" + Binder.getCallingPid()
6141 + ") when getting content provider " + name);
6142 }
6143 }
6144
6145 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006146 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006147 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006148 boolean providerRunning = cpr != null;
6149 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006151 String msg;
6152 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6153 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
6155
6156 if (r != null && cpr.canRunHere(r)) {
6157 // This provider has been published or is in the process
6158 // of being published... but it is also allowed to run
6159 // in the caller's process, so don't make a connection
6160 // and just let the caller instantiate its own instance.
6161 if (cpr.provider != null) {
6162 // don't give caller the provider object, it needs
6163 // to make its own.
6164 cpr = new ContentProviderRecord(cpr);
6165 }
6166 return cpr;
6167 }
6168
6169 final long origId = Binder.clearCallingIdentity();
6170
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006171 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006173 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006174 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006175 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006176 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006177 // make sure to count it as being accessed and thus
6178 // back up on the LRU list. This is good because
6179 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006180 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006181 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006182 }
6183
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006184 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006185 if (false) {
6186 if (cpr.name.flattenToShortString().equals(
6187 "com.android.providers.calendar/.CalendarProvider2")) {
6188 Slog.v(TAG, "****************** KILLING "
6189 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006190 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006191 }
6192 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006193 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006194 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6195 // NOTE: there is still a race here where a signal could be
6196 // pending on the process even though we managed to update its
6197 // adj level. Not sure what to do about this, but at least
6198 // the race is now smaller.
6199 if (!success) {
6200 // Uh oh... it looks like the provider's process
6201 // has been killed on us. We need to wait for a new
6202 // process to be started, and make sure its death
6203 // doesn't kill our process.
6204 Slog.i(TAG,
6205 "Existing provider " + cpr.name.flattenToShortString()
6206 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006207 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006208 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006209 if (!lastRef) {
6210 // This wasn't the last ref our process had on
6211 // the provider... we have now been killed, bail.
6212 return null;
6213 }
6214 providerRunning = false;
6215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 }
6217
6218 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006221 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006223 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006224 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006225 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 } catch (RemoteException ex) {
6227 }
6228 if (cpi == null) {
6229 return null;
6230 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006231 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6232 userId = 0;
6233 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006234 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006235
Dianne Hackbornb424b632010-08-18 15:59:05 -07006236 String msg;
6237 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6238 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 }
6240
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006241 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006242 && !cpi.processName.equals("system")) {
6243 // If this content provider does not run in the system
6244 // process, and the system is not yet ready to run other
6245 // processes, then fail fast instead of hanging.
6246 throw new IllegalArgumentException(
6247 "Attempt to launch content provider before system ready");
6248 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006249
6250 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006251 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 final boolean firstClass = cpr == null;
6253 if (firstClass) {
6254 try {
6255 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006256 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 getApplicationInfo(
6258 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006259 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006261 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 + cpi.name);
6263 return null;
6264 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006265 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006266 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 } catch (RemoteException ex) {
6268 // pm is in same process, this will never happen.
6269 }
6270 }
6271
6272 if (r != null && cpr.canRunHere(r)) {
6273 // If this is a multiprocess provider, then just return its
6274 // info and allow the caller to instantiate it. Only do
6275 // this if the provider is the same user as the caller's
6276 // process, or can run as root (so can be in any process).
6277 return cpr;
6278 }
6279
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006280 if (DEBUG_PROVIDER) {
6281 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006282 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006283 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 }
6285
6286 // This is single process, and our app is now connecting to it.
6287 // See if we are already in the process of launching this
6288 // provider.
6289 final int N = mLaunchingProviders.size();
6290 int i;
6291 for (i=0; i<N; i++) {
6292 if (mLaunchingProviders.get(i) == cpr) {
6293 break;
6294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 }
6296
6297 // If the provider is not already being launched, then get it
6298 // started.
6299 if (i >= N) {
6300 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006301
6302 try {
6303 // Content provider is now in use, its package can't be stopped.
6304 try {
6305 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006306 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006307 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006308 } catch (IllegalArgumentException e) {
6309 Slog.w(TAG, "Failed trying to unstop package "
6310 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006311 }
6312
6313 ProcessRecord proc = startProcessLocked(cpi.processName,
6314 cpr.appInfo, false, 0, "content provider",
6315 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006316 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006317 if (proc == null) {
6318 Slog.w(TAG, "Unable to launch app "
6319 + cpi.applicationInfo.packageName + "/"
6320 + cpi.applicationInfo.uid + " for provider "
6321 + name + ": process is bad");
6322 return null;
6323 }
6324 cpr.launchingApp = proc;
6325 mLaunchingProviders.add(cpr);
6326 } finally {
6327 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 }
6330
6331 // Make sure the provider is published (the same provider class
6332 // may be published under multiple names).
6333 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006334 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006336
Amith Yamasani742a6712011-05-04 14:49:28 -07006337 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006338 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 }
6340 }
6341
6342 // Wait for the provider to be published...
6343 synchronized (cpr) {
6344 while (cpr.provider == null) {
6345 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006346 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 + cpi.applicationInfo.packageName + "/"
6348 + cpi.applicationInfo.uid + " for provider "
6349 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006350 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 cpi.applicationInfo.packageName,
6352 cpi.applicationInfo.uid, name);
6353 return null;
6354 }
6355 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006356 if (DEBUG_MU) {
6357 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6358 + cpr.launchingApp);
6359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 cpr.wait();
6361 } catch (InterruptedException ex) {
6362 }
6363 }
6364 }
6365 return cpr;
6366 }
6367
6368 public final ContentProviderHolder getContentProvider(
6369 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006370 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 if (caller == null) {
6372 String msg = "null IApplicationThread when getting content provider "
6373 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006374 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 throw new SecurityException(msg);
6376 }
6377
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006378 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 }
6380
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006381 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6382 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6383 "Do not have permission in call getContentProviderExternal()");
6384 return getContentProviderExternalUnchecked(name, token);
6385 }
6386
6387 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6388 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 }
6390
6391 /**
6392 * Drop a content provider from a ProcessRecord's bookkeeping
6393 * @param cpr
6394 */
6395 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006396 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006398 int userId = UserId.getUserId(Binder.getCallingUid());
6399 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006401 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006402 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006403 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 return;
6405 }
6406 final ProcessRecord r = getRecordForAppLocked(caller);
6407 if (r == null) {
6408 throw new SecurityException(
6409 "Unable to find app for caller " + caller +
6410 " when removing content provider " + name);
6411 }
6412 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006413 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006414 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6415 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6416 + r.info.processName + " from process "
6417 + localCpr.appInfo.processName);
6418 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006420 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006421 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 return;
6423 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006424 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006425 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 }
6429 }
6430
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006431 public void removeContentProviderExternal(String name, IBinder token) {
6432 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6433 "Do not have permission in call removeContentProviderExternal()");
6434 removeContentProviderExternalUnchecked(name, token);
6435 }
6436
6437 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006439 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6440 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 if(cpr == null) {
6442 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006443 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 return;
6445 }
6446
6447 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006448 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006449 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6450 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006451 if (localCpr.hasExternalProcessHandles()) {
6452 if (localCpr.removeExternalProcessHandleLocked(token)) {
6453 updateOomAdjLocked();
6454 } else {
6455 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6456 + " with no external reference for token: "
6457 + token + ".");
6458 }
6459 } else {
6460 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6461 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 }
6464 }
6465
6466 public final void publishContentProviders(IApplicationThread caller,
6467 List<ContentProviderHolder> providers) {
6468 if (providers == null) {
6469 return;
6470 }
6471
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006472 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 synchronized(this) {
6474 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006475 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006476 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 if (r == null) {
6478 throw new SecurityException(
6479 "Unable to find app for caller " + caller
6480 + " (pid=" + Binder.getCallingPid()
6481 + ") when publishing content providers");
6482 }
6483
6484 final long origId = Binder.clearCallingIdentity();
6485
6486 final int N = providers.size();
6487 for (int i=0; i<N; i++) {
6488 ContentProviderHolder src = providers.get(i);
6489 if (src == null || src.info == null || src.provider == null) {
6490 continue;
6491 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006492 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006493 if (DEBUG_MU)
6494 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006496 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006497 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 String names[] = dst.info.authority.split(";");
6499 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006500 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 }
6502
6503 int NL = mLaunchingProviders.size();
6504 int j;
6505 for (j=0; j<NL; j++) {
6506 if (mLaunchingProviders.get(j) == dst) {
6507 mLaunchingProviders.remove(j);
6508 j--;
6509 NL--;
6510 }
6511 }
6512 synchronized (dst) {
6513 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006514 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 dst.notifyAll();
6516 }
6517 updateOomAdjLocked(r);
6518 }
6519 }
6520
6521 Binder.restoreCallingIdentity(origId);
6522 }
6523 }
6524
6525 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006526 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006527 synchronized (mSelf) {
6528 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6529 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006530 if (providers != null) {
6531 for (int i=providers.size()-1; i>=0; i--) {
6532 ProviderInfo pi = (ProviderInfo)providers.get(i);
6533 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6534 Slog.w(TAG, "Not installing system proc provider " + pi.name
6535 + ": not system .apk");
6536 providers.remove(i);
6537 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006538 }
6539 }
6540 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006541 if (providers != null) {
6542 mSystemThread.installSystemProviders(providers);
6543 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006544
6545 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006546
6547 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 }
6549
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006550 /**
6551 * Allows app to retrieve the MIME type of a URI without having permission
6552 * to access its content provider.
6553 *
6554 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6555 *
6556 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6557 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6558 */
6559 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006560 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006561 final String name = uri.getAuthority();
6562 final long ident = Binder.clearCallingIdentity();
6563 ContentProviderHolder holder = null;
6564
6565 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006566 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006567 if (holder != null) {
6568 return holder.provider.getType(uri);
6569 }
6570 } catch (RemoteException e) {
6571 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6572 return null;
6573 } finally {
6574 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006575 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006576 }
6577 Binder.restoreCallingIdentity(ident);
6578 }
6579
6580 return null;
6581 }
6582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 // =========================================================
6584 // GLOBAL MANAGEMENT
6585 // =========================================================
6586
6587 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006588 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 String proc = customProcess != null ? customProcess : info.processName;
6590 BatteryStatsImpl.Uid.Proc ps = null;
6591 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006592 int uid = info.uid;
6593 if (isolated) {
6594 int userId = UserId.getUserId(uid);
6595 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6596 uid = 0;
6597 while (true) {
6598 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6599 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6600 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6601 }
6602 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6603 mNextIsolatedProcessUid++;
6604 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6605 // No process for this uid, use it.
6606 break;
6607 }
6608 stepsLeft--;
6609 if (stepsLeft <= 0) {
6610 return null;
6611 }
6612 }
6613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 synchronized (stats) {
6615 ps = stats.getProcessStatsLocked(info.uid, proc);
6616 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006617 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006620 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6621 ProcessRecord app;
6622 if (!isolated) {
6623 app = getProcessRecordLocked(info.processName, info.uid);
6624 } else {
6625 app = null;
6626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627
6628 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006629 app = newProcessRecordLocked(null, info, null, isolated);
6630 mProcessNames.put(info.processName, app.uid, app);
6631 if (isolated) {
6632 mIsolatedProcesses.put(app.uid, app);
6633 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006634 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 }
6636
Dianne Hackborne7f97212011-02-24 14:40:20 -08006637 // This package really, really can not be stopped.
6638 try {
6639 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006640 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006641 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006642 } catch (IllegalArgumentException e) {
6643 Slog.w(TAG, "Failed trying to unstop package "
6644 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006645 }
6646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6648 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6649 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006650 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 }
6652 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6653 mPersistentStartingProcesses.add(app);
6654 startProcessLocked(app, "added application", app.processName);
6655 }
6656
6657 return app;
6658 }
6659
6660 public void unhandledBack() {
6661 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6662 "unhandledBack()");
6663
6664 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006665 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006666 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 TAG, "Performing unhandledBack(): stack size = " + count);
6668 if (count > 1) {
6669 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006670 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6672 Binder.restoreCallingIdentity(origId);
6673 }
6674 }
6675 }
6676
6677 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006678 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006680 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 ParcelFileDescriptor pfd = null;
6682 if (cph != null) {
6683 // We record the binder invoker's uid in thread-local storage before
6684 // going to the content provider to open the file. Later, in the code
6685 // that handles all permissions checks, we look for this uid and use
6686 // that rather than the Activity Manager's own uid. The effect is that
6687 // we do the check against the caller's permissions even though it looks
6688 // to the content provider like the Activity Manager itself is making
6689 // the request.
6690 sCallerIdentity.set(new Identity(
6691 Binder.getCallingPid(), Binder.getCallingUid()));
6692 try {
6693 pfd = cph.provider.openFile(uri, "r");
6694 } catch (FileNotFoundException e) {
6695 // do nothing; pfd will be returned null
6696 } finally {
6697 // Ensure that whatever happens, we clean up the identity state
6698 sCallerIdentity.remove();
6699 }
6700
6701 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006702 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006704 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 }
6706 return pfd;
6707 }
6708
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006709 // Actually is sleeping or shutting down or whatever else in the future
6710 // is an inactive state.
6711 public boolean isSleeping() {
6712 return mSleeping || mShuttingDown;
6713 }
6714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006716 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6717 != PackageManager.PERMISSION_GRANTED) {
6718 throw new SecurityException("Requires permission "
6719 + android.Manifest.permission.DEVICE_POWER);
6720 }
6721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006723 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006724 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006726 if (!mSleeping) {
6727 mSleeping = true;
6728 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006729
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006730 // Initialize the wake times of all processes.
6731 checkExcessivePowerUsageLocked(false);
6732 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6733 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6734 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 }
6737 }
6738
Dianne Hackborn55280a92009-05-07 15:53:46 -07006739 public boolean shutdown(int timeout) {
6740 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6741 != PackageManager.PERMISSION_GRANTED) {
6742 throw new SecurityException("Requires permission "
6743 + android.Manifest.permission.SHUTDOWN);
6744 }
6745
6746 boolean timedout = false;
6747
6748 synchronized(this) {
6749 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006750 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006751
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006752 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006753 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006754 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006755 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006756 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006757 long delay = endTime - System.currentTimeMillis();
6758 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006759 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006760 timedout = true;
6761 break;
6762 }
6763 try {
6764 this.wait();
6765 } catch (InterruptedException e) {
6766 }
6767 }
6768 }
6769 }
6770
6771 mUsageStatsService.shutdown();
6772 mBatteryStatsService.shutdown();
6773
6774 return timedout;
6775 }
6776
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006777 public final void activitySlept(IBinder token) {
6778 if (localLOGV) Slog.v(
6779 TAG, "Activity slept: token=" + token);
6780
6781 ActivityRecord r = null;
6782
6783 final long origId = Binder.clearCallingIdentity();
6784
6785 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006786 r = mMainStack.isInStackLocked(token);
6787 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006788 mMainStack.activitySleptLocked(r);
6789 }
6790 }
6791
6792 Binder.restoreCallingIdentity(origId);
6793 }
6794
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006795 private void comeOutOfSleepIfNeededLocked() {
6796 if (!mWentToSleep && !mLockScreenShown) {
6797 if (mSleeping) {
6798 mSleeping = false;
6799 mMainStack.awakeFromSleepingLocked();
6800 mMainStack.resumeTopActivityLocked(null);
6801 }
6802 }
6803 }
6804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006806 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6807 != PackageManager.PERMISSION_GRANTED) {
6808 throw new SecurityException("Requires permission "
6809 + android.Manifest.permission.DEVICE_POWER);
6810 }
6811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006812 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006813 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006814 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006815 comeOutOfSleepIfNeededLocked();
6816 }
6817 }
6818
Jeff Brownc042ee22012-05-08 13:03:42 -07006819 private void updateEventDispatchingLocked() {
6820 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6821 }
6822
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006823 public void setLockScreenShown(boolean shown) {
6824 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6825 != PackageManager.PERMISSION_GRANTED) {
6826 throw new SecurityException("Requires permission "
6827 + android.Manifest.permission.DEVICE_POWER);
6828 }
6829
6830 synchronized(this) {
6831 mLockScreenShown = shown;
6832 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 }
6834 }
6835
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006836 public void stopAppSwitches() {
6837 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6838 != PackageManager.PERMISSION_GRANTED) {
6839 throw new SecurityException("Requires permission "
6840 + android.Manifest.permission.STOP_APP_SWITCHES);
6841 }
6842
6843 synchronized(this) {
6844 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6845 + APP_SWITCH_DELAY_TIME;
6846 mDidAppSwitch = false;
6847 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6848 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6849 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6850 }
6851 }
6852
6853 public void resumeAppSwitches() {
6854 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6855 != PackageManager.PERMISSION_GRANTED) {
6856 throw new SecurityException("Requires permission "
6857 + android.Manifest.permission.STOP_APP_SWITCHES);
6858 }
6859
6860 synchronized(this) {
6861 // Note that we don't execute any pending app switches... we will
6862 // let those wait until either the timeout, or the next start
6863 // activity request.
6864 mAppSwitchesAllowedTime = 0;
6865 }
6866 }
6867
6868 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6869 String name) {
6870 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6871 return true;
6872 }
6873
6874 final int perm = checkComponentPermission(
6875 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006876 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006877 if (perm == PackageManager.PERMISSION_GRANTED) {
6878 return true;
6879 }
6880
Joe Onorato8a9b2202010-02-26 18:56:32 -08006881 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006882 return false;
6883 }
6884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 public void setDebugApp(String packageName, boolean waitForDebugger,
6886 boolean persistent) {
6887 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6888 "setDebugApp()");
6889
6890 // Note that this is not really thread safe if there are multiple
6891 // callers into it at the same time, but that's not a situation we
6892 // care about.
6893 if (persistent) {
6894 final ContentResolver resolver = mContext.getContentResolver();
6895 Settings.System.putString(
6896 resolver, Settings.System.DEBUG_APP,
6897 packageName);
6898 Settings.System.putInt(
6899 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6900 waitForDebugger ? 1 : 0);
6901 }
6902
6903 synchronized (this) {
6904 if (!persistent) {
6905 mOrigDebugApp = mDebugApp;
6906 mOrigWaitForDebugger = mWaitForDebugger;
6907 }
6908 mDebugApp = packageName;
6909 mWaitForDebugger = waitForDebugger;
6910 mDebugTransient = !persistent;
6911 if (packageName != null) {
6912 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006913 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006914 Binder.restoreCallingIdentity(origId);
6915 }
6916 }
6917 }
6918
Siva Velusamy92a8b222012-03-09 16:24:04 -08006919 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6920 synchronized (this) {
6921 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6922 if (!isDebuggable) {
6923 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6924 throw new SecurityException("Process not debuggable: " + app.packageName);
6925 }
6926 }
6927
6928 mOpenGlTraceApp = processName;
6929 }
6930 }
6931
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006932 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6933 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6934 synchronized (this) {
6935 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6936 if (!isDebuggable) {
6937 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6938 throw new SecurityException("Process not debuggable: " + app.packageName);
6939 }
6940 }
6941 mProfileApp = processName;
6942 mProfileFile = profileFile;
6943 if (mProfileFd != null) {
6944 try {
6945 mProfileFd.close();
6946 } catch (IOException e) {
6947 }
6948 mProfileFd = null;
6949 }
6950 mProfileFd = profileFd;
6951 mProfileType = 0;
6952 mAutoStopProfiler = autoStopProfiler;
6953 }
6954 }
6955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 public void setAlwaysFinish(boolean enabled) {
6957 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6958 "setAlwaysFinish()");
6959
6960 Settings.System.putInt(
6961 mContext.getContentResolver(),
6962 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6963
6964 synchronized (this) {
6965 mAlwaysFinishActivities = enabled;
6966 }
6967 }
6968
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006969 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006971 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006972 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006973 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006974 }
6975 }
6976
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006977 public boolean isUserAMonkey() {
6978 // For now the fact that there is a controller implies
6979 // we have a monkey.
6980 synchronized (this) {
6981 return mController != null;
6982 }
6983 }
6984
Jeff Sharkeya4620792011-05-20 15:29:23 -07006985 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006986 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6987 "registerProcessObserver()");
6988 synchronized (this) {
6989 mProcessObservers.register(observer);
6990 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006991 }
6992
6993 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006994 synchronized (this) {
6995 mProcessObservers.unregister(observer);
6996 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006997 }
6998
Daniel Sandler69a48172010-06-23 16:29:36 -04006999 public void setImmersive(IBinder token, boolean immersive) {
7000 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007001 ActivityRecord r = mMainStack.isInStackLocked(token);
7002 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007003 throw new IllegalArgumentException();
7004 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007005 r.immersive = immersive;
7006 }
7007 }
7008
7009 public boolean isImmersive(IBinder token) {
7010 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007011 ActivityRecord r = mMainStack.isInStackLocked(token);
7012 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007013 throw new IllegalArgumentException();
7014 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007015 return r.immersive;
7016 }
7017 }
7018
7019 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007020 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007021 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007022 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007023 return (r != null) ? r.immersive : false;
7024 }
7025 }
7026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 public final void enterSafeMode() {
7028 synchronized(this) {
7029 // It only makes sense to do this before the system is ready
7030 // and started launching other packages.
7031 if (!mSystemReady) {
7032 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007033 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 } catch (RemoteException e) {
7035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 }
7037 }
7038 }
7039
Jeff Brownb09abc12011-01-13 21:08:27 -08007040 public final void showSafeModeOverlay() {
7041 View v = LayoutInflater.from(mContext).inflate(
7042 com.android.internal.R.layout.safe_mode, null);
7043 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7044 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7045 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7046 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7047 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7048 lp.format = v.getBackground().getOpacity();
7049 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7050 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7051 ((WindowManager)mContext.getSystemService(
7052 Context.WINDOW_SERVICE)).addView(v, lp);
7053 }
7054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 public void noteWakeupAlarm(IIntentSender sender) {
7056 if (!(sender instanceof PendingIntentRecord)) {
7057 return;
7058 }
7059 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7060 synchronized (stats) {
7061 if (mBatteryStatsService.isOnBattery()) {
7062 mBatteryStatsService.enforceCallingPermission();
7063 PendingIntentRecord rec = (PendingIntentRecord)sender;
7064 int MY_UID = Binder.getCallingUid();
7065 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7066 BatteryStatsImpl.Uid.Pkg pkg =
7067 stats.getPackageStatsLocked(uid, rec.key.packageName);
7068 pkg.incWakeupsLocked();
7069 }
7070 }
7071 }
7072
Dianne Hackborn64825172011-03-02 21:32:58 -08007073 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007075 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007077 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 // XXX Note: don't acquire main activity lock here, because the window
7079 // manager calls in with its locks held.
7080
7081 boolean killed = false;
7082 synchronized (mPidsSelfLocked) {
7083 int[] types = new int[pids.length];
7084 int worstType = 0;
7085 for (int i=0; i<pids.length; i++) {
7086 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7087 if (proc != null) {
7088 int type = proc.setAdj;
7089 types[i] = type;
7090 if (type > worstType) {
7091 worstType = type;
7092 }
7093 }
7094 }
7095
Dianne Hackborn64825172011-03-02 21:32:58 -08007096 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007098 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7099 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007100 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007102
7103 // If this is not a secure call, don't let it kill processes that
7104 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007105 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7106 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007107 }
7108
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007109 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 for (int i=0; i<pids.length; i++) {
7111 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7112 if (proc == null) {
7113 continue;
7114 }
7115 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007116 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007117 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007118 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7119 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007121 proc.killedBackground = true;
7122 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 }
7124 }
7125 }
7126 return killed;
7127 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007128
7129 @Override
7130 public boolean killProcessesBelowForeground(String reason) {
7131 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7132 throw new SecurityException("killProcessesBelowForeground() only available to system");
7133 }
7134
7135 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7136 }
7137
7138 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7139 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7140 throw new SecurityException("killProcessesBelowAdj() only available to system");
7141 }
7142
7143 boolean killed = false;
7144 synchronized (mPidsSelfLocked) {
7145 final int size = mPidsSelfLocked.size();
7146 for (int i = 0; i < size; i++) {
7147 final int pid = mPidsSelfLocked.keyAt(i);
7148 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7149 if (proc == null) continue;
7150
7151 final int adj = proc.setAdj;
7152 if (adj > belowAdj && !proc.killedBackground) {
7153 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7154 EventLog.writeEvent(
7155 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7156 killed = true;
7157 proc.killedBackground = true;
7158 Process.killProcessQuiet(pid);
7159 }
7160 }
7161 }
7162 return killed;
7163 }
7164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165 public final void startRunning(String pkg, String cls, String action,
7166 String data) {
7167 synchronized(this) {
7168 if (mStartRunning) {
7169 return;
7170 }
7171 mStartRunning = true;
7172 mTopComponent = pkg != null && cls != null
7173 ? new ComponentName(pkg, cls) : null;
7174 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7175 mTopData = data;
7176 if (!mSystemReady) {
7177 return;
7178 }
7179 }
7180
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007181 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 }
7183
7184 private void retrieveSettings() {
7185 final ContentResolver resolver = mContext.getContentResolver();
7186 String debugApp = Settings.System.getString(
7187 resolver, Settings.System.DEBUG_APP);
7188 boolean waitForDebugger = Settings.System.getInt(
7189 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7190 boolean alwaysFinishActivities = Settings.System.getInt(
7191 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7192
7193 Configuration configuration = new Configuration();
7194 Settings.System.getConfiguration(resolver, configuration);
7195
7196 synchronized (this) {
7197 mDebugApp = mOrigDebugApp = debugApp;
7198 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7199 mAlwaysFinishActivities = alwaysFinishActivities;
7200 // This happens before any activities are started, so we can
7201 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007202 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007203 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 }
7205 }
7206
7207 public boolean testIsSystemReady() {
7208 // no need to synchronize(this) just to read & return the value
7209 return mSystemReady;
7210 }
7211
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007212 private static File getCalledPreBootReceiversFile() {
7213 File dataDir = Environment.getDataDirectory();
7214 File systemDir = new File(dataDir, "system");
7215 File fname = new File(systemDir, "called_pre_boots.dat");
7216 return fname;
7217 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007218
7219 static final int LAST_DONE_VERSION = 10000;
7220
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007221 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7222 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7223 File file = getCalledPreBootReceiversFile();
7224 FileInputStream fis = null;
7225 try {
7226 fis = new FileInputStream(file);
7227 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007228 int fvers = dis.readInt();
7229 if (fvers == LAST_DONE_VERSION) {
7230 String vers = dis.readUTF();
7231 String codename = dis.readUTF();
7232 String build = dis.readUTF();
7233 if (android.os.Build.VERSION.RELEASE.equals(vers)
7234 && android.os.Build.VERSION.CODENAME.equals(codename)
7235 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7236 int num = dis.readInt();
7237 while (num > 0) {
7238 num--;
7239 String pkg = dis.readUTF();
7240 String cls = dis.readUTF();
7241 lastDoneReceivers.add(new ComponentName(pkg, cls));
7242 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007243 }
7244 }
7245 } catch (FileNotFoundException e) {
7246 } catch (IOException e) {
7247 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7248 } finally {
7249 if (fis != null) {
7250 try {
7251 fis.close();
7252 } catch (IOException e) {
7253 }
7254 }
7255 }
7256 return lastDoneReceivers;
7257 }
7258
7259 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7260 File file = getCalledPreBootReceiversFile();
7261 FileOutputStream fos = null;
7262 DataOutputStream dos = null;
7263 try {
7264 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7265 fos = new FileOutputStream(file);
7266 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007267 dos.writeInt(LAST_DONE_VERSION);
7268 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007269 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007270 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007271 dos.writeInt(list.size());
7272 for (int i=0; i<list.size(); i++) {
7273 dos.writeUTF(list.get(i).getPackageName());
7274 dos.writeUTF(list.get(i).getClassName());
7275 }
7276 } catch (IOException e) {
7277 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7278 file.delete();
7279 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007280 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007281 if (dos != null) {
7282 try {
7283 dos.close();
7284 } catch (IOException e) {
7285 // TODO Auto-generated catch block
7286 e.printStackTrace();
7287 }
7288 }
7289 }
7290 }
7291
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007292 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007293 synchronized(this) {
7294 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007295 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 return;
7297 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007298
7299 // Check to see if there are any update receivers to run.
7300 if (!mDidUpdate) {
7301 if (mWaitingUpdate) {
7302 return;
7303 }
7304 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7305 List<ResolveInfo> ris = null;
7306 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007307 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007308 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007309 } catch (RemoteException e) {
7310 }
7311 if (ris != null) {
7312 for (int i=ris.size()-1; i>=0; i--) {
7313 if ((ris.get(i).activityInfo.applicationInfo.flags
7314 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7315 ris.remove(i);
7316 }
7317 }
7318 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007319
7320 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7321
7322 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007323 for (int i=0; i<ris.size(); i++) {
7324 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007325 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7326 if (lastDoneReceivers.contains(comp)) {
7327 ris.remove(i);
7328 i--;
7329 }
7330 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007331
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007332 for (int i=0; i<ris.size(); i++) {
7333 ActivityInfo ai = ris.get(i).activityInfo;
7334 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7335 doneReceivers.add(comp);
7336 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007337 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007338 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007339 finisher = new IIntentReceiver.Stub() {
7340 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007341 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007342 boolean sticky) {
7343 // The raw IIntentReceiver interface is called
7344 // with the AM lock held, so redispatch to
7345 // execute our code without the lock.
7346 mHandler.post(new Runnable() {
7347 public void run() {
7348 synchronized (ActivityManagerService.this) {
7349 mDidUpdate = true;
7350 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007351 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007352 showBootMessage(mContext.getText(
7353 R.string.android_upgrading_complete),
7354 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007355 systemReady(goingCallback);
7356 }
7357 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007358 }
7359 };
7360 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007361 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007362 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007363 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007364 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007365 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007366 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007367 mWaitingUpdate = true;
7368 }
7369 }
7370 }
7371 if (mWaitingUpdate) {
7372 return;
7373 }
7374 mDidUpdate = true;
7375 }
7376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 mSystemReady = true;
7378 if (!mStartRunning) {
7379 return;
7380 }
7381 }
7382
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007383 ArrayList<ProcessRecord> procsToKill = null;
7384 synchronized(mPidsSelfLocked) {
7385 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7386 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7387 if (!isAllowedWhileBooting(proc.info)){
7388 if (procsToKill == null) {
7389 procsToKill = new ArrayList<ProcessRecord>();
7390 }
7391 procsToKill.add(proc);
7392 }
7393 }
7394 }
7395
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007396 synchronized(this) {
7397 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007398 for (int i=procsToKill.size()-1; i>=0; i--) {
7399 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007400 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007401 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007402 }
7403 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007404
7405 // Now that we have cleaned up any update processes, we
7406 // are ready to start launching real processes and know that
7407 // we won't trample on them any more.
7408 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007409 }
7410
Joe Onorato8a9b2202010-02-26 18:56:32 -08007411 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007412 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 SystemClock.uptimeMillis());
7414
7415 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007416 // Make sure we have no pre-ready processes sitting around.
7417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7419 ResolveInfo ri = mContext.getPackageManager()
7420 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007421 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 CharSequence errorMsg = null;
7423 if (ri != null) {
7424 ActivityInfo ai = ri.activityInfo;
7425 ApplicationInfo app = ai.applicationInfo;
7426 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7427 mTopAction = Intent.ACTION_FACTORY_TEST;
7428 mTopData = null;
7429 mTopComponent = new ComponentName(app.packageName,
7430 ai.name);
7431 } else {
7432 errorMsg = mContext.getResources().getText(
7433 com.android.internal.R.string.factorytest_not_system);
7434 }
7435 } else {
7436 errorMsg = mContext.getResources().getText(
7437 com.android.internal.R.string.factorytest_no_action);
7438 }
7439 if (errorMsg != null) {
7440 mTopAction = null;
7441 mTopData = null;
7442 mTopComponent = null;
7443 Message msg = Message.obtain();
7444 msg.what = SHOW_FACTORY_ERROR_MSG;
7445 msg.getData().putCharSequence("msg", errorMsg);
7446 mHandler.sendMessage(msg);
7447 }
7448 }
7449 }
7450
7451 retrieveSettings();
7452
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007453 if (goingCallback != null) goingCallback.run();
7454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 synchronized (this) {
7456 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7457 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007458 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007459 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 if (apps != null) {
7461 int N = apps.size();
7462 int i;
7463 for (i=0; i<N; i++) {
7464 ApplicationInfo info
7465 = (ApplicationInfo)apps.get(i);
7466 if (info != null &&
7467 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007468 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 }
7470 }
7471 }
7472 } catch (RemoteException ex) {
7473 // pm is in same process, this will never happen.
7474 }
7475 }
7476
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007477 // Start up initial activity.
7478 mBooting = true;
7479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007481 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 Message msg = Message.obtain();
7483 msg.what = SHOW_UID_ERROR_MSG;
7484 mHandler.sendMessage(msg);
7485 }
7486 } catch (RemoteException e) {
7487 }
7488
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007489 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007490 }
7491 }
7492
Dan Egnorb7f03672009-12-09 16:22:32 -08007493 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007494 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007495 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007496 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007497 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007498 startAppProblemLocked(app);
7499 app.stopFreezingAllLocked();
7500 return handleAppCrashLocked(app);
7501 }
7502
Dan Egnorb7f03672009-12-09 16:22:32 -08007503 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007504 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007506 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007507 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7508 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 startAppProblemLocked(app);
7510 app.stopFreezingAllLocked();
7511 }
7512
7513 /**
7514 * Generate a process error record, suitable for attachment to a ProcessRecord.
7515 *
7516 * @param app The ProcessRecord in which the error occurred.
7517 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7518 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007519 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 * @param shortMsg Short message describing the crash.
7521 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007522 * @param stackTrace Full crash stack trace, may be null.
7523 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 * @return Returns a fully-formed AppErrorStateInfo record.
7525 */
7526 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007527 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007528 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 report.condition = condition;
7531 report.processName = app.processName;
7532 report.pid = app.pid;
7533 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007534 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535 report.shortMsg = shortMsg;
7536 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007537 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538
7539 return report;
7540 }
7541
Dan Egnor42471dd2010-01-07 17:25:22 -08007542 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 synchronized (this) {
7544 app.crashing = false;
7545 app.crashingReport = null;
7546 app.notResponding = false;
7547 app.notRespondingReport = null;
7548 if (app.anrDialog == fromDialog) {
7549 app.anrDialog = null;
7550 }
7551 if (app.waitDialog == fromDialog) {
7552 app.waitDialog = null;
7553 }
7554 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007555 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007556 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007557 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7558 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007559 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 }
7562 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007563
Dan Egnorb7f03672009-12-09 16:22:32 -08007564 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007565 if (mHeadless) {
7566 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7567 return false;
7568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 long now = SystemClock.uptimeMillis();
7570
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007571 Long crashTime;
7572 if (!app.isolated) {
7573 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7574 } else {
7575 crashTime = null;
7576 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007577 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007579 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007581 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007582 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007583 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7584 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007586 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007588 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 }
7590 }
7591 if (!app.persistent) {
7592 // We don't want to start this process again until the user
7593 // explicitly does so... but for persistent process, we really
7594 // need to keep it running. If a persistent process is actually
7595 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007596 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007598 if (!app.isolated) {
7599 // XXX We don't have a way to mark isolated processes
7600 // as bad, since they don't have a peristent identity.
7601 mBadProcesses.put(app.info.processName, app.uid, now);
7602 mProcessCrashTimes.remove(app.info.processName, app.uid);
7603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007606 // Don't let services in this process be restarted and potentially
7607 // annoy the user repeatedly. Unless it is persistent, since those
7608 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007609 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007610 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 return false;
7612 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007613 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007614 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007615 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007616 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007617 // If the top running activity is from this crashing
7618 // process, then terminate it to avoid getting in a loop.
7619 Slog.w(TAG, " Force finishing activity "
7620 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007621 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007622 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007623 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007624 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007625 // stopped, to avoid a situation where one will get
7626 // re-start our crashing activity once it gets resumed again.
7627 index--;
7628 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007629 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007630 if (r.state == ActivityState.RESUMED
7631 || r.state == ActivityState.PAUSING
7632 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007633 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007634 Slog.w(TAG, " Force finishing activity "
7635 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007636 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007637 Activity.RESULT_CANCELED, null, "crashed");
7638 }
7639 }
7640 }
7641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 }
7643
7644 // Bump up the crash count of any services currently running in the proc.
7645 if (app.services.size() != 0) {
7646 // Any services running in the application need to be placed
7647 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007648 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007650 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 sr.crashCount++;
7652 }
7653 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007654
7655 // If the crashing process is what we consider to be the "home process" and it has been
7656 // replaced by a third-party app, clear the package preferred activities from packages
7657 // with a home activity running in the process to prevent a repeatedly crashing app
7658 // from blocking the user to manually clear the list.
7659 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7660 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7661 Iterator it = mHomeProcess.activities.iterator();
7662 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007663 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007664 if (r.isHomeActivity) {
7665 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7666 try {
7667 ActivityThread.getPackageManager()
7668 .clearPackagePreferredActivities(r.packageName);
7669 } catch (RemoteException c) {
7670 // pm is in same process, this will never happen.
7671 }
7672 }
7673 }
7674 }
7675
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007676 if (!app.isolated) {
7677 // XXX Can't keep track of crash times for isolated processes,
7678 // because they don't have a perisistent identity.
7679 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7680 }
7681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 return true;
7683 }
7684
7685 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007686 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7687 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 skipCurrentReceiverLocked(app);
7689 }
7690
7691 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007692 for (BroadcastQueue queue : mBroadcastQueues) {
7693 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694 }
7695 }
7696
Dan Egnor60d87622009-12-16 16:32:58 -08007697 /**
7698 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7699 * The application process will exit immediately after this call returns.
7700 * @param app object of the crashing app, null for the system server
7701 * @param crashInfo describing the exception
7702 */
7703 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007704 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007705 final String processName = app == null ? "system_server"
7706 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007707
7708 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007709 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007710 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007711 crashInfo.exceptionClassName,
7712 crashInfo.exceptionMessage,
7713 crashInfo.throwFileName,
7714 crashInfo.throwLineNumber);
7715
Jeff Sharkeya353d262011-10-28 11:12:06 -07007716 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007717
7718 crashApplication(r, crashInfo);
7719 }
7720
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007721 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007722 IBinder app,
7723 int violationMask,
7724 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007725 ProcessRecord r = findAppProcess(app, "StrictMode");
7726 if (r == null) {
7727 return;
7728 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007729
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007730 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007731 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007732 boolean logIt = true;
7733 synchronized (mAlreadyLoggedViolatedStacks) {
7734 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7735 logIt = false;
7736 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007737 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007738 // the relative pain numbers, without logging all
7739 // the stack traces repeatedly. We'd want to do
7740 // likewise in the client code, which also does
7741 // dup suppression, before the Binder call.
7742 } else {
7743 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7744 mAlreadyLoggedViolatedStacks.clear();
7745 }
7746 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7747 }
7748 }
7749 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007750 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007751 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007752 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007753
7754 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7755 AppErrorResult result = new AppErrorResult();
7756 synchronized (this) {
7757 final long origId = Binder.clearCallingIdentity();
7758
7759 Message msg = Message.obtain();
7760 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7761 HashMap<String, Object> data = new HashMap<String, Object>();
7762 data.put("result", result);
7763 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007764 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007765 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007766 msg.obj = data;
7767 mHandler.sendMessage(msg);
7768
7769 Binder.restoreCallingIdentity(origId);
7770 }
7771 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007772 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007773 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007774 }
7775
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007776 // Depending on the policy in effect, there could be a bunch of
7777 // these in quick succession so we try to batch these together to
7778 // minimize disk writes, number of dropbox entries, and maximize
7779 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007780 private void logStrictModeViolationToDropBox(
7781 ProcessRecord process,
7782 StrictMode.ViolationInfo info) {
7783 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007784 return;
7785 }
7786 final boolean isSystemApp = process == null ||
7787 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7788 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007789 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007790 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7791 final DropBoxManager dbox = (DropBoxManager)
7792 mContext.getSystemService(Context.DROPBOX_SERVICE);
7793
7794 // Exit early if the dropbox isn't configured to accept this report type.
7795 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7796
7797 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007798 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007799 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7800 synchronized (sb) {
7801 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007802 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007803 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7804 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007805 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7806 if (info.violationNumThisLoop != 0) {
7807 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7808 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007809 if (info.numAnimationsRunning != 0) {
7810 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7811 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007812 if (info.broadcastIntentAction != null) {
7813 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7814 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007815 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007816 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007817 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007818 if (info.numInstances != -1) {
7819 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7820 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007821 if (info.tags != null) {
7822 for (String tag : info.tags) {
7823 sb.append("Span-Tag: ").append(tag).append("\n");
7824 }
7825 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007826 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007827 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7828 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007829 }
7830 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007831
7832 // Only buffer up to ~64k. Various logging bits truncate
7833 // things at 128k.
7834 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007835 }
7836
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007837 // Flush immediately if the buffer's grown too large, or this
7838 // is a non-system app. Non-system apps are isolated with a
7839 // different tag & policy and not batched.
7840 //
7841 // Batching is useful during internal testing with
7842 // StrictMode settings turned up high. Without batching,
7843 // thousands of separate files could be created on boot.
7844 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007845 new Thread("Error dump: " + dropboxTag) {
7846 @Override
7847 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007848 String report;
7849 synchronized (sb) {
7850 report = sb.toString();
7851 sb.delete(0, sb.length());
7852 sb.trimToSize();
7853 }
7854 if (report.length() != 0) {
7855 dbox.addText(dropboxTag, report);
7856 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007857 }
7858 }.start();
7859 return;
7860 }
7861
7862 // System app batching:
7863 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007864 // An existing dropbox-writing thread is outstanding, so
7865 // we don't need to start it up. The existing thread will
7866 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007867 return;
7868 }
7869
7870 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7871 // (After this point, we shouldn't access AMS internal data structures.)
7872 new Thread("Error dump: " + dropboxTag) {
7873 @Override
7874 public void run() {
7875 // 5 second sleep to let stacks arrive and be batched together
7876 try {
7877 Thread.sleep(5000); // 5 seconds
7878 } catch (InterruptedException e) {}
7879
7880 String errorReport;
7881 synchronized (mStrictModeBuffer) {
7882 errorReport = mStrictModeBuffer.toString();
7883 if (errorReport.length() == 0) {
7884 return;
7885 }
7886 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7887 mStrictModeBuffer.trimToSize();
7888 }
7889 dbox.addText(dropboxTag, errorReport);
7890 }
7891 }.start();
7892 }
7893
Dan Egnor60d87622009-12-16 16:32:58 -08007894 /**
7895 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7896 * @param app object of the crashing app, null for the system server
7897 * @param tag reported by the caller
7898 * @param crashInfo describing the context of the error
7899 * @return true if the process should exit immediately (WTF is fatal)
7900 */
7901 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007902 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007903 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007904 final String processName = app == null ? "system_server"
7905 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007906
7907 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007908 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007909 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007910 tag, crashInfo.exceptionMessage);
7911
Jeff Sharkeya353d262011-10-28 11:12:06 -07007912 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007913
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007914 if (r != null && r.pid != Process.myPid() &&
7915 Settings.Secure.getInt(mContext.getContentResolver(),
7916 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007917 crashApplication(r, crashInfo);
7918 return true;
7919 } else {
7920 return false;
7921 }
7922 }
7923
7924 /**
7925 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7926 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7927 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007928 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007929 if (app == null) {
7930 return null;
7931 }
7932
7933 synchronized (this) {
7934 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7935 final int NA = apps.size();
7936 for (int ia=0; ia<NA; ia++) {
7937 ProcessRecord p = apps.valueAt(ia);
7938 if (p.thread != null && p.thread.asBinder() == app) {
7939 return p;
7940 }
7941 }
7942 }
7943
Dianne Hackborncb44d962011-03-10 17:02:27 -08007944 Slog.w(TAG, "Can't find mystery application for " + reason
7945 + " from pid=" + Binder.getCallingPid()
7946 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007947 return null;
7948 }
7949 }
7950
7951 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007952 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7953 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007954 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007955 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7956 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007957 // Watchdog thread ends up invoking this function (with
7958 // a null ProcessRecord) to add the stack file to dropbox.
7959 // Do not acquire a lock on this (am) in such cases, as it
7960 // could cause a potential deadlock, if and when watchdog
7961 // is invoked due to unavailability of lock on am and it
7962 // would prevent watchdog from killing system_server.
7963 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007964 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007965 return;
7966 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007967 // Note: ProcessRecord 'process' is guarded by the service
7968 // instance. (notably process.pkgList, which could otherwise change
7969 // concurrently during execution of this method)
7970 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007971 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007972 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007973 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007974 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7975 for (String pkg : process.pkgList) {
7976 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007977 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007978 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007979 if (pi != null) {
7980 sb.append(" v").append(pi.versionCode);
7981 if (pi.versionName != null) {
7982 sb.append(" (").append(pi.versionName).append(")");
7983 }
7984 }
7985 } catch (RemoteException e) {
7986 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007987 }
Dan Egnora455d192010-03-12 08:52:28 -08007988 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007989 }
Dan Egnora455d192010-03-12 08:52:28 -08007990 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007991 }
7992
7993 private static String processClass(ProcessRecord process) {
7994 if (process == null || process.pid == MY_PID) {
7995 return "system_server";
7996 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7997 return "system_app";
7998 } else {
7999 return "data_app";
8000 }
8001 }
8002
8003 /**
8004 * Write a description of an error (crash, WTF, ANR) to the drop box.
8005 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8006 * @param process which caused the error, null means the system server
8007 * @param activity which triggered the error, null if unknown
8008 * @param parent activity related to the error, null if unknown
8009 * @param subject line related to the error, null if absent
8010 * @param report in long form describing the error, null if absent
8011 * @param logFile to include in the report, null if none
8012 * @param crashInfo giving an application stack trace, null if absent
8013 */
8014 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008015 ProcessRecord process, String processName, ActivityRecord activity,
8016 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008017 final String report, final File logFile,
8018 final ApplicationErrorReport.CrashInfo crashInfo) {
8019 // NOTE -- this must never acquire the ActivityManagerService lock,
8020 // otherwise the watchdog may be prevented from resetting the system.
8021
8022 final String dropboxTag = processClass(process) + "_" + eventType;
8023 final DropBoxManager dbox = (DropBoxManager)
8024 mContext.getSystemService(Context.DROPBOX_SERVICE);
8025
8026 // Exit early if the dropbox isn't configured to accept this report type.
8027 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8028
8029 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008030 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008031 if (activity != null) {
8032 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8033 }
8034 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8035 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8036 }
8037 if (parent != null && parent != activity) {
8038 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8039 }
8040 if (subject != null) {
8041 sb.append("Subject: ").append(subject).append("\n");
8042 }
8043 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008044 if (Debug.isDebuggerConnected()) {
8045 sb.append("Debugger: Connected\n");
8046 }
Dan Egnora455d192010-03-12 08:52:28 -08008047 sb.append("\n");
8048
8049 // Do the rest in a worker thread to avoid blocking the caller on I/O
8050 // (After this point, we shouldn't access AMS internal data structures.)
8051 Thread worker = new Thread("Error dump: " + dropboxTag) {
8052 @Override
8053 public void run() {
8054 if (report != null) {
8055 sb.append(report);
8056 }
8057 if (logFile != null) {
8058 try {
8059 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8060 } catch (IOException e) {
8061 Slog.e(TAG, "Error reading " + logFile, e);
8062 }
8063 }
8064 if (crashInfo != null && crashInfo.stackTrace != null) {
8065 sb.append(crashInfo.stackTrace);
8066 }
8067
8068 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8069 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8070 if (lines > 0) {
8071 sb.append("\n");
8072
8073 // Merge several logcat streams, and take the last N lines
8074 InputStreamReader input = null;
8075 try {
8076 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8077 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8078 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8079
8080 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8081 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8082 input = new InputStreamReader(logcat.getInputStream());
8083
8084 int num;
8085 char[] buf = new char[8192];
8086 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8087 } catch (IOException e) {
8088 Slog.e(TAG, "Error running logcat", e);
8089 } finally {
8090 if (input != null) try { input.close(); } catch (IOException e) {}
8091 }
8092 }
8093
8094 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008095 }
Dan Egnora455d192010-03-12 08:52:28 -08008096 };
8097
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008098 if (process == null) {
8099 // If process is null, we are being called from some internal code
8100 // and may be about to die -- run this synchronously.
8101 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008102 } else {
8103 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008104 }
8105 }
8106
8107 /**
8108 * Bring up the "unexpected error" dialog box for a crashing app.
8109 * Deal with edge cases (intercepts from instrumented applications,
8110 * ActivityController, error intent receivers, that sort of thing).
8111 * @param r the application crashing
8112 * @param crashInfo describing the failure
8113 */
8114 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008115 long timeMillis = System.currentTimeMillis();
8116 String shortMsg = crashInfo.exceptionClassName;
8117 String longMsg = crashInfo.exceptionMessage;
8118 String stackTrace = crashInfo.stackTrace;
8119 if (shortMsg != null && longMsg != null) {
8120 longMsg = shortMsg + ": " + longMsg;
8121 } else if (shortMsg != null) {
8122 longMsg = shortMsg;
8123 }
8124
Dan Egnor60d87622009-12-16 16:32:58 -08008125 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008127 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 try {
8129 String name = r != null ? r.processName : null;
8130 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008131 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008132 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008133 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 + " at watcher's request");
8135 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008136 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 }
8138 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008139 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 }
8141 }
8142
8143 final long origId = Binder.clearCallingIdentity();
8144
8145 // If this process is running instrumentation, finish it.
8146 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008147 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008149 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8150 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 Bundle info = new Bundle();
8152 info.putString("shortMsg", shortMsg);
8153 info.putString("longMsg", longMsg);
8154 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8155 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008156 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 }
8158
Dan Egnor60d87622009-12-16 16:32:58 -08008159 // If we can't identify the process or it's already exceeded its crash quota,
8160 // quit right away without showing a crash dialog.
8161 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008163 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008164 }
8165
8166 Message msg = Message.obtain();
8167 msg.what = SHOW_ERROR_MSG;
8168 HashMap data = new HashMap();
8169 data.put("result", result);
8170 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 msg.obj = data;
8172 mHandler.sendMessage(msg);
8173
8174 Binder.restoreCallingIdentity(origId);
8175 }
8176
8177 int res = result.get();
8178
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008179 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008181 if (r != null && !r.isolated) {
8182 // XXX Can't keep track of crash time for isolated processes,
8183 // since they don't have a persistent identity.
8184 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 SystemClock.uptimeMillis());
8186 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008187 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008188 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008189 }
8190 }
8191
8192 if (appErrorIntent != null) {
8193 try {
8194 mContext.startActivity(appErrorIntent);
8195 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008196 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008200
8201 Intent createAppErrorIntentLocked(ProcessRecord r,
8202 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8203 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008204 if (report == null) {
8205 return null;
8206 }
8207 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8208 result.setComponent(r.errorReportReceiver);
8209 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8210 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8211 return result;
8212 }
8213
Dan Egnorb7f03672009-12-09 16:22:32 -08008214 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8215 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008216 if (r.errorReportReceiver == null) {
8217 return null;
8218 }
8219
8220 if (!r.crashing && !r.notResponding) {
8221 return null;
8222 }
8223
Dan Egnorb7f03672009-12-09 16:22:32 -08008224 ApplicationErrorReport report = new ApplicationErrorReport();
8225 report.packageName = r.info.packageName;
8226 report.installerPackageName = r.errorReportReceiver.getPackageName();
8227 report.processName = r.processName;
8228 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008229 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008230
Dan Egnorb7f03672009-12-09 16:22:32 -08008231 if (r.crashing) {
8232 report.type = ApplicationErrorReport.TYPE_CRASH;
8233 report.crashInfo = crashInfo;
8234 } else if (r.notResponding) {
8235 report.type = ApplicationErrorReport.TYPE_ANR;
8236 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008237
Dan Egnorb7f03672009-12-09 16:22:32 -08008238 report.anrInfo.activity = r.notRespondingReport.tag;
8239 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8240 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008241 }
8242
Dan Egnorb7f03672009-12-09 16:22:32 -08008243 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008244 }
8245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008247 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 // assume our apps are happy - lazy create the list
8249 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8250
8251 synchronized (this) {
8252
8253 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008254 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8255 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008256 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8257 // This one's in trouble, so we'll generate a report for it
8258 // crashes are higher priority (in case there's a crash *and* an anr)
8259 ActivityManager.ProcessErrorStateInfo report = null;
8260 if (app.crashing) {
8261 report = app.crashingReport;
8262 } else if (app.notResponding) {
8263 report = app.notRespondingReport;
8264 }
8265
8266 if (report != null) {
8267 if (errList == null) {
8268 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8269 }
8270 errList.add(report);
8271 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008272 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 " crashing = " + app.crashing +
8274 " notResponding = " + app.notResponding);
8275 }
8276 }
8277 }
8278 }
8279
8280 return errList;
8281 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008282
8283 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008284 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008285 if (currApp != null) {
8286 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8287 }
8288 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008289 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8290 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008291 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8292 if (currApp != null) {
8293 currApp.lru = 0;
8294 }
8295 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008296 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008297 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8298 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8299 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8300 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8301 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8302 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8303 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8304 } else {
8305 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8306 }
8307 }
8308
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008309 private void fillInProcMemInfo(ProcessRecord app,
8310 ActivityManager.RunningAppProcessInfo outInfo) {
8311 outInfo.pid = app.pid;
8312 outInfo.uid = app.info.uid;
8313 if (mHeavyWeightProcess == app) {
8314 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8315 }
8316 if (app.persistent) {
8317 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8318 }
8319 outInfo.lastTrimLevel = app.trimMemoryLevel;
8320 int adj = app.curAdj;
8321 outInfo.importance = oomAdjToImportance(adj, outInfo);
8322 outInfo.importanceReasonCode = app.adjTypeCode;
8323 }
8324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008326 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008327 // Lazy instantiation of list
8328 List<ActivityManager.RunningAppProcessInfo> runList = null;
8329 synchronized (this) {
8330 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008331 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8332 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8334 // Generate process state info for running application
8335 ActivityManager.RunningAppProcessInfo currApp =
8336 new ActivityManager.RunningAppProcessInfo(app.processName,
8337 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008338 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008339 if (app.adjSource instanceof ProcessRecord) {
8340 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008341 currApp.importanceReasonImportance = oomAdjToImportance(
8342 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008343 } else if (app.adjSource instanceof ActivityRecord) {
8344 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008345 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8346 }
8347 if (app.adjTarget instanceof ComponentName) {
8348 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8349 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008350 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 // + " lru=" + currApp.lru);
8352 if (runList == null) {
8353 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8354 }
8355 runList.add(currApp);
8356 }
8357 }
8358 }
8359 return runList;
8360 }
8361
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008362 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008363 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008364 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8365 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8366 if (runningApps != null && runningApps.size() > 0) {
8367 Set<String> extList = new HashSet<String>();
8368 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8369 if (app.pkgList != null) {
8370 for (String pkg : app.pkgList) {
8371 extList.add(pkg);
8372 }
8373 }
8374 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008375 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008376 for (String pkg : extList) {
8377 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008378 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008379 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8380 retList.add(info);
8381 }
8382 } catch (RemoteException e) {
8383 }
8384 }
8385 }
8386 return retList;
8387 }
8388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008389 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008390 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8391 enforceNotIsolatedCaller("getMyMemoryState");
8392 synchronized (this) {
8393 ProcessRecord proc;
8394 synchronized (mPidsSelfLocked) {
8395 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8396 }
8397 fillInProcMemInfo(proc, outInfo);
8398 }
8399 }
8400
8401 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008403 if (checkCallingPermission(android.Manifest.permission.DUMP)
8404 != PackageManager.PERMISSION_GRANTED) {
8405 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8406 + Binder.getCallingPid()
8407 + ", uid=" + Binder.getCallingUid()
8408 + " without permission "
8409 + android.Manifest.permission.DUMP);
8410 return;
8411 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008412
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008413 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008414 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008415 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008416
8417 int opti = 0;
8418 while (opti < args.length) {
8419 String opt = args[opti];
8420 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8421 break;
8422 }
8423 opti++;
8424 if ("-a".equals(opt)) {
8425 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008426 } else if ("-c".equals(opt)) {
8427 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008428 } else if ("-h".equals(opt)) {
8429 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008430 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008431 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008432 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008433 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8434 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8435 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008436 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008437 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008438 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008439 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008440 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008441 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008442 pw.println(" all: dump all activities");
8443 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008444 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008445 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8446 pw.println(" a partial substring in a component name, a");
8447 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008448 pw.println(" -a: include all available server state.");
8449 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008451 } else {
8452 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008454 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008455
8456 long origId = Binder.clearCallingIdentity();
8457 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008458 // Is the caller requesting to dump a particular piece of data?
8459 if (opti < args.length) {
8460 String cmd = args[opti];
8461 opti++;
8462 if ("activities".equals(cmd) || "a".equals(cmd)) {
8463 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008464 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008465 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008466 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008467 String[] newArgs;
8468 String name;
8469 if (opti >= args.length) {
8470 name = null;
8471 newArgs = EMPTY_STRING_ARRAY;
8472 } else {
8473 name = args[opti];
8474 opti++;
8475 newArgs = new String[args.length - opti];
8476 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8477 args.length - opti);
8478 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008479 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008480 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008481 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008482 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008483 String[] newArgs;
8484 String name;
8485 if (opti >= args.length) {
8486 name = null;
8487 newArgs = EMPTY_STRING_ARRAY;
8488 } else {
8489 name = args[opti];
8490 opti++;
8491 newArgs = new String[args.length - opti];
8492 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8493 args.length - opti);
8494 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008495 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008496 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008497 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008498 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008499 String[] newArgs;
8500 String name;
8501 if (opti >= args.length) {
8502 name = null;
8503 newArgs = EMPTY_STRING_ARRAY;
8504 } else {
8505 name = args[opti];
8506 opti++;
8507 newArgs = new String[args.length - opti];
8508 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8509 args.length - opti);
8510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008511 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008512 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008513 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008514 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8515 synchronized (this) {
8516 dumpOomLocked(fd, pw, args, opti, true);
8517 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008518 } else if ("provider".equals(cmd)) {
8519 String[] newArgs;
8520 String name;
8521 if (opti >= args.length) {
8522 name = null;
8523 newArgs = EMPTY_STRING_ARRAY;
8524 } else {
8525 name = args[opti];
8526 opti++;
8527 newArgs = new String[args.length - opti];
8528 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8529 }
8530 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8531 pw.println("No providers match: " + name);
8532 pw.println("Use -h for help.");
8533 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8535 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008536 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008539 String[] newArgs;
8540 String name;
8541 if (opti >= args.length) {
8542 name = null;
8543 newArgs = EMPTY_STRING_ARRAY;
8544 } else {
8545 name = args[opti];
8546 opti++;
8547 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008548 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8549 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008550 }
8551 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8552 pw.println("No services match: " + name);
8553 pw.println("Use -h for help.");
8554 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 } else if ("package".equals(cmd)) {
8556 String[] newArgs;
8557 if (opti >= args.length) {
8558 pw.println("package: no package name specified");
8559 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008560 } else {
8561 dumpPackage = args[opti];
8562 opti++;
8563 newArgs = new String[args.length - opti];
8564 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8565 args.length - opti);
8566 args = newArgs;
8567 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008568 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008569 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008570 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8571 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008572 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008574 } else {
8575 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008576 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8577 pw.println("Bad activity command, or no activities match: " + cmd);
8578 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008579 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008580 }
8581 if (!more) {
8582 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008583 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008586
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008587 // No piece of data specified, dump everything.
8588 synchronized (this) {
8589 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008590 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008591 if (needSep) {
8592 pw.println(" ");
8593 }
8594 if (dumpAll) {
8595 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008596 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008597 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008598 if (needSep) {
8599 pw.println(" ");
8600 }
8601 if (dumpAll) {
8602 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008603 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008604 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605 if (needSep) {
8606 pw.println(" ");
8607 }
8608 if (dumpAll) {
8609 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008610 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008611 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008612 if (needSep) {
8613 pw.println(" ");
8614 }
8615 if (dumpAll) {
8616 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008617 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008618 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008619 if (needSep) {
8620 pw.println(" ");
8621 }
8622 if (dumpAll) {
8623 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008624 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008625 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008626 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008627 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008628 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008629
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008630 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008631 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008632 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8633 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008634 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8635 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008636 pw.println(" ");
8637 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008638 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8639 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008640 if (mMainStack.mWaitingVisibleActivities.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 for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008643 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008644 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008645 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008646 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008647 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008648 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008649 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008650 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008651 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008652 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8653 pw.println(" ");
8654 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008655 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008656 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008657 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008658 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 pw.println(" ");
8660 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008661 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008662 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008665 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008666 if (mMainStack.mPausingActivity != null) {
8667 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008668 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008669 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008670 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008671 if (dumpAll) {
8672 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8673 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008674 pw.println(" mDismissKeyguardOnNextActivity: "
8675 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008678 if (mRecentTasks.size() > 0) {
8679 pw.println();
8680 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008681
8682 final int N = mRecentTasks.size();
8683 for (int i=0; i<N; i++) {
8684 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008685 if (dumpPackage != null) {
8686 if (tr.realActivity == null ||
8687 !dumpPackage.equals(tr.realActivity)) {
8688 continue;
8689 }
8690 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008691 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8692 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008693 if (dumpAll) {
8694 mRecentTasks.get(i).dump(pw, " ");
8695 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008696 }
8697 }
8698
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008699 if (dumpAll) {
8700 pw.println(" ");
8701 pw.println(" mCurTask: " + mCurTask);
8702 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008703
8704 return true;
8705 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008706
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008707 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008708 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008709 boolean needSep = false;
8710 int numPers = 0;
8711
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008712 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8713
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008714 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8716 final int NA = procs.size();
8717 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 ProcessRecord r = procs.valueAt(ia);
8719 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8720 continue;
8721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 if (!needSep) {
8723 pw.println(" All known processes:");
8724 needSep = true;
8725 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008726 pw.print(r.persistent ? " *PERS*" : " *APP*");
8727 pw.print(" UID "); pw.print(procs.keyAt(ia));
8728 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 r.dump(pw, " ");
8730 if (r.persistent) {
8731 numPers++;
8732 }
8733 }
8734 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008735 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008736
8737 if (mIsolatedProcesses.size() > 0) {
8738 if (needSep) pw.println(" ");
8739 needSep = true;
8740 pw.println(" Isolated process list (sorted by uid):");
8741 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8742 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8743 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8744 continue;
8745 }
8746 pw.println(String.format("%sIsolated #%2d: %s",
8747 " ", i, r.toString()));
8748 }
8749 }
8750
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 if (mLruProcesses.size() > 0) {
8752 if (needSep) pw.println(" ");
8753 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008754 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008755 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008756 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008757 needSep = true;
8758 }
8759
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008760 if (dumpAll) {
8761 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008762 boolean printed = false;
8763 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8764 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8765 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8766 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008767 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008768 if (!printed) {
8769 if (needSep) pw.println(" ");
8770 needSep = true;
8771 pw.println(" PID mappings:");
8772 printed = true;
8773 }
8774 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8775 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 }
8777 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778 }
8779
8780 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008781 synchronized (mPidsSelfLocked) {
8782 boolean printed = false;
8783 for (int i=0; i<mForegroundProcesses.size(); i++) {
8784 ProcessRecord r = mPidsSelfLocked.get(
8785 mForegroundProcesses.valueAt(i).pid);
8786 if (dumpPackage != null && (r == null
8787 || !dumpPackage.equals(r.info.packageName))) {
8788 continue;
8789 }
8790 if (!printed) {
8791 if (needSep) pw.println(" ");
8792 needSep = true;
8793 pw.println(" Foreground Processes:");
8794 printed = true;
8795 }
8796 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8797 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008800 }
8801
8802 if (mPersistentStartingProcesses.size() > 0) {
8803 if (needSep) pw.println(" ");
8804 needSep = true;
8805 pw.println(" Persisent processes that are starting:");
8806 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008807 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810 if (mRemovedProcesses.size() > 0) {
8811 if (needSep) pw.println(" ");
8812 needSep = true;
8813 pw.println(" Processes that are being removed:");
8814 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008815 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008816 }
8817
8818 if (mProcessesOnHold.size() > 0) {
8819 if (needSep) pw.println(" ");
8820 needSep = true;
8821 pw.println(" Processes that are on old until the system is ready:");
8822 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008823 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008825
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008826 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008827
8828 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008829 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008830 long now = SystemClock.uptimeMillis();
8831 for (Map.Entry<String, SparseArray<Long>> procs
8832 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008833 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 SparseArray<Long> uids = procs.getValue();
8835 final int N = uids.size();
8836 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008837 int puid = uids.keyAt(i);
8838 ProcessRecord r = mProcessNames.get(pname, puid);
8839 if (dumpPackage != null && (r == null
8840 || !dumpPackage.equals(r.info.packageName))) {
8841 continue;
8842 }
8843 if (!printed) {
8844 if (needSep) pw.println(" ");
8845 needSep = true;
8846 pw.println(" Time since processes crashed:");
8847 printed = true;
8848 }
8849 pw.print(" Process "); pw.print(pname);
8850 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008852 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8853 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008854 }
8855 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008858 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008859 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008860 for (Map.Entry<String, SparseArray<Long>> procs
8861 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008862 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008863 SparseArray<Long> uids = procs.getValue();
8864 final int N = uids.size();
8865 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008866 int puid = uids.keyAt(i);
8867 ProcessRecord r = mProcessNames.get(pname, puid);
8868 if (dumpPackage != null && (r == null
8869 || !dumpPackage.equals(r.info.packageName))) {
8870 continue;
8871 }
8872 if (!printed) {
8873 if (needSep) pw.println(" ");
8874 needSep = true;
8875 pw.println(" Bad processes:");
8876 }
8877 pw.print(" Bad process "); pw.print(pname);
8878 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008879 pw.print(": crashed at time ");
8880 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 }
8882 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008885 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008886 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008887 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008888 if (dumpAll) {
8889 StringBuilder sb = new StringBuilder(128);
8890 sb.append(" mPreviousProcessVisibleTime: ");
8891 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8892 pw.println(sb);
8893 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008894 if (mHeavyWeightProcess != null) {
8895 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8896 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008897 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008898 if (dumpAll) {
8899 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008900 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008901 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008902 for (Map.Entry<String, Integer> entry
8903 : mCompatModePackages.getPackages().entrySet()) {
8904 String pkg = entry.getKey();
8905 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008906 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8907 continue;
8908 }
8909 if (!printed) {
8910 pw.println(" mScreenCompatPackages:");
8911 printed = true;
8912 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008913 pw.print(" "); pw.print(pkg); pw.print(": ");
8914 pw.print(mode); pw.println();
8915 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008916 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008917 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008918 if (mSleeping || mWentToSleep || mLockScreenShown) {
8919 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8920 + " mLockScreenShown " + mLockScreenShown);
8921 }
8922 if (mShuttingDown) {
8923 pw.println(" mShuttingDown=" + mShuttingDown);
8924 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008925 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8926 || mOrigWaitForDebugger) {
8927 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8928 + " mDebugTransient=" + mDebugTransient
8929 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8930 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008931 if (mOpenGlTraceApp != null) {
8932 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8933 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008934 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8935 || mProfileFd != null) {
8936 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8937 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8938 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8939 + mAutoStopProfiler);
8940 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008941 if (mAlwaysFinishActivities || mController != null) {
8942 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8943 + " mController=" + mController);
8944 }
8945 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008948 + " mProcessesReady=" + mProcessesReady
8949 + " mSystemReady=" + mSystemReady);
8950 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 + " mBooted=" + mBooted
8952 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008953 pw.print(" mLastPowerCheckRealtime=");
8954 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8955 pw.println("");
8956 pw.print(" mLastPowerCheckUptime=");
8957 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8958 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008959 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8960 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008961 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008962 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8963 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008965
8966 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 }
8968
Dianne Hackborn287952c2010-09-22 22:34:31 -07008969 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008970 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008971 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008972 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008973 long now = SystemClock.uptimeMillis();
8974 for (int i=0; i<mProcessesToGc.size(); i++) {
8975 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008976 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8977 continue;
8978 }
8979 if (!printed) {
8980 if (needSep) pw.println(" ");
8981 needSep = true;
8982 pw.println(" Processes that are waiting to GC:");
8983 printed = true;
8984 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008985 pw.print(" Process "); pw.println(proc);
8986 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8987 pw.print(", last gced=");
8988 pw.print(now-proc.lastRequestedGc);
8989 pw.print(" ms ago, last lowMem=");
8990 pw.print(now-proc.lastLowMemory);
8991 pw.println(" ms ago");
8992
8993 }
8994 }
8995 return needSep;
8996 }
8997
8998 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8999 int opti, boolean dumpAll) {
9000 boolean needSep = false;
9001
9002 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009003 if (needSep) pw.println(" ");
9004 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009005 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009006 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009007 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009008 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9009 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9010 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9011 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9012 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009013 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009014 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009015 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009016 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009017 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009018 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009019
9020 if (needSep) pw.println(" ");
9021 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009022 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009023 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009024 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009025 needSep = true;
9026 }
9027
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009028 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009029
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009030 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009031 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009032 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009033 if (mHeavyWeightProcess != null) {
9034 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9035 }
9036
9037 return true;
9038 }
9039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 /**
9041 * There are three ways to call this:
9042 * - no service specified: dump all the services
9043 * - a flattened component name that matched an existing service was specified as the
9044 * first arg: dump that one service
9045 * - the first arg isn't the flattened component name of an existing service:
9046 * dump all services whose component contains the first arg as a substring
9047 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009048 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9049 int opti, boolean dumpAll) {
9050 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009051
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009052 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009053 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009054 try {
9055 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9056 for (UserInfo user : users) {
9057 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9058 services.add(r1);
9059 }
9060 }
9061 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009062 }
9063 }
9064 } else {
9065 ComponentName componentName = name != null
9066 ? ComponentName.unflattenFromString(name) : null;
9067 int objectId = 0;
9068 if (componentName == null) {
9069 // Not a '/' separated full component name; maybe an object ID?
9070 try {
9071 objectId = Integer.parseInt(name, 16);
9072 name = null;
9073 componentName = null;
9074 } catch (RuntimeException e) {
9075 }
9076 }
9077
9078 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009079 try {
9080 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9081 for (UserInfo user : users) {
9082 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9083 if (componentName != null) {
9084 if (r1.name.equals(componentName)) {
9085 services.add(r1);
9086 }
9087 } else if (name != null) {
9088 if (r1.name.flattenToString().contains(name)) {
9089 services.add(r1);
9090 }
9091 } else if (System.identityHashCode(r1) == objectId) {
9092 services.add(r1);
9093 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009094 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009095 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009096 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097 }
9098 }
9099 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009100
9101 if (services.size() <= 0) {
9102 return false;
9103 }
9104
9105 boolean needSep = false;
9106 for (int i=0; i<services.size(); i++) {
9107 if (needSep) {
9108 pw.println();
9109 }
9110 needSep = true;
9111 dumpService("", fd, pw, services.get(i), args, dumpAll);
9112 }
9113 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 }
9115
9116 /**
9117 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9118 * there is a thread associated with the service.
9119 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009120 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9121 final ServiceRecord r, String[] args, boolean dumpAll) {
9122 String innerPrefix = prefix + " ";
9123 synchronized (this) {
9124 pw.print(prefix); pw.print("SERVICE ");
9125 pw.print(r.shortName); pw.print(" ");
9126 pw.print(Integer.toHexString(System.identityHashCode(r)));
9127 pw.print(" pid=");
9128 if (r.app != null) pw.println(r.app.pid);
9129 else pw.println("(not running)");
9130 if (dumpAll) {
9131 r.dump(pw, innerPrefix);
9132 }
9133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009135 pw.print(prefix); pw.println(" Client:");
9136 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009137 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009138 TransferPipe tp = new TransferPipe();
9139 try {
9140 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9141 tp.setBufferPrefix(prefix + " ");
9142 tp.go(fd);
9143 } finally {
9144 tp.kill();
9145 }
9146 } catch (IOException e) {
9147 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009148 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009149 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009150 }
9151 }
9152 }
9153
Marco Nelissen18cb2872011-11-15 11:19:53 -08009154 /**
9155 * There are three ways to call this:
9156 * - no provider specified: dump all the providers
9157 * - a flattened component name that matched an existing provider was specified as the
9158 * first arg: dump that one provider
9159 * - the first arg isn't the flattened component name of an existing provider:
9160 * dump all providers whose component contains the first arg as a substring
9161 */
9162 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9163 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009164 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009165 }
9166
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009167 static class ItemMatcher {
9168 ArrayList<ComponentName> components;
9169 ArrayList<String> strings;
9170 ArrayList<Integer> objects;
9171 boolean all;
9172
9173 ItemMatcher() {
9174 all = true;
9175 }
9176
9177 void build(String name) {
9178 ComponentName componentName = ComponentName.unflattenFromString(name);
9179 if (componentName != null) {
9180 if (components == null) {
9181 components = new ArrayList<ComponentName>();
9182 }
9183 components.add(componentName);
9184 all = false;
9185 } else {
9186 int objectId = 0;
9187 // Not a '/' separated full component name; maybe an object ID?
9188 try {
9189 objectId = Integer.parseInt(name, 16);
9190 if (objects == null) {
9191 objects = new ArrayList<Integer>();
9192 }
9193 objects.add(objectId);
9194 all = false;
9195 } catch (RuntimeException e) {
9196 // Not an integer; just do string match.
9197 if (strings == null) {
9198 strings = new ArrayList<String>();
9199 }
9200 strings.add(name);
9201 all = false;
9202 }
9203 }
9204 }
9205
9206 int build(String[] args, int opti) {
9207 for (; opti<args.length; opti++) {
9208 String name = args[opti];
9209 if ("--".equals(name)) {
9210 return opti+1;
9211 }
9212 build(name);
9213 }
9214 return opti;
9215 }
9216
9217 boolean match(Object object, ComponentName comp) {
9218 if (all) {
9219 return true;
9220 }
9221 if (components != null) {
9222 for (int i=0; i<components.size(); i++) {
9223 if (components.get(i).equals(comp)) {
9224 return true;
9225 }
9226 }
9227 }
9228 if (objects != null) {
9229 for (int i=0; i<objects.size(); i++) {
9230 if (System.identityHashCode(object) == objects.get(i)) {
9231 return true;
9232 }
9233 }
9234 }
9235 if (strings != null) {
9236 String flat = comp.flattenToString();
9237 for (int i=0; i<strings.size(); i++) {
9238 if (flat.contains(strings.get(i))) {
9239 return true;
9240 }
9241 }
9242 }
9243 return false;
9244 }
9245 }
9246
Dianne Hackborn625ac272010-09-17 18:29:22 -07009247 /**
9248 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009249 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009250 * - the cmd arg isn't the flattened component name of an existing activity:
9251 * dump all activity whose component contains the cmd as a substring
9252 * - A hex number of the ActivityRecord object instance.
9253 */
9254 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9255 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009256 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009257
9258 if ("all".equals(name)) {
9259 synchronized (this) {
9260 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009261 activities.add(r1);
9262 }
9263 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009264 } else if ("top".equals(name)) {
9265 synchronized (this) {
9266 final int N = mMainStack.mHistory.size();
9267 if (N > 0) {
9268 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9269 }
9270 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009271 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009272 ItemMatcher matcher = new ItemMatcher();
9273 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009274
9275 synchronized (this) {
9276 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009277 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009278 activities.add(r1);
9279 }
9280 }
9281 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009282 }
9283
9284 if (activities.size() <= 0) {
9285 return false;
9286 }
9287
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009288 String[] newArgs = new String[args.length - opti];
9289 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9290
Dianne Hackborn30d71892010-12-11 10:37:55 -08009291 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009292 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009293 for (int i=activities.size()-1; i>=0; i--) {
9294 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009295 if (needSep) {
9296 pw.println();
9297 }
9298 needSep = true;
9299 synchronized (this) {
9300 if (lastTask != r.task) {
9301 lastTask = r.task;
9302 pw.print("TASK "); pw.print(lastTask.affinity);
9303 pw.print(" id="); pw.println(lastTask.taskId);
9304 if (dumpAll) {
9305 lastTask.dump(pw, " ");
9306 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009307 }
9308 }
9309 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009310 }
9311 return true;
9312 }
9313
9314 /**
9315 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9316 * there is a thread associated with the activity.
9317 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009318 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009319 final ActivityRecord r, String[] args, boolean dumpAll) {
9320 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009321 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009322 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9323 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9324 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009325 if (r.app != null) pw.println(r.app.pid);
9326 else pw.println("(not running)");
9327 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009328 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009329 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009330 }
9331 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009332 // flush anything that is already in the PrintWriter since the thread is going
9333 // to write to the file descriptor directly
9334 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009335 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009336 TransferPipe tp = new TransferPipe();
9337 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009338 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9339 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009340 tp.go(fd);
9341 } finally {
9342 tp.kill();
9343 }
9344 } catch (IOException e) {
9345 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009346 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009348 }
9349 }
9350 }
9351
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009352 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009353 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009354 boolean needSep = false;
9355
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009356 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009359 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360 Iterator it = mRegisteredReceivers.values().iterator();
9361 while (it.hasNext()) {
9362 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009363 if (dumpPackage != null && (r.app == null ||
9364 !dumpPackage.equals(r.app.info.packageName))) {
9365 continue;
9366 }
9367 if (!printed) {
9368 pw.println(" Registered Receivers:");
9369 needSep = true;
9370 printed = true;
9371 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009372 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 r.dump(pw, " ");
9374 }
9375 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376
9377 if (mReceiverResolver.dump(pw, needSep ?
9378 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9379 " ", dumpPackage, false)) {
9380 needSep = true;
9381 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009382 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009383
9384 for (BroadcastQueue q : mBroadcastQueues) {
9385 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009388 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009389
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009390 if (mStickyBroadcasts != null && dumpPackage == null) {
9391 if (needSep) {
9392 pw.println();
9393 }
9394 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009395 pw.println(" Sticky broadcasts:");
9396 StringBuilder sb = new StringBuilder(128);
9397 for (Map.Entry<String, ArrayList<Intent>> ent
9398 : mStickyBroadcasts.entrySet()) {
9399 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009400 if (dumpAll) {
9401 pw.println(":");
9402 ArrayList<Intent> intents = ent.getValue();
9403 final int N = intents.size();
9404 for (int i=0; i<N; i++) {
9405 sb.setLength(0);
9406 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009407 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009408 pw.println(sb.toString());
9409 Bundle bundle = intents.get(i).getExtras();
9410 if (bundle != null) {
9411 pw.print(" ");
9412 pw.println(bundle.toString());
9413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009415 } else {
9416 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417 }
9418 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009419 needSep = true;
9420 }
9421
9422 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009423 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009424 for (BroadcastQueue queue : mBroadcastQueues) {
9425 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9426 + queue.mBroadcastsScheduled);
9427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 pw.println(" mHandler:");
9429 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009430 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009432
9433 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 }
9435
Marco Nelissen18cb2872011-11-15 11:19:53 -08009436 /**
9437 * Prints a list of ServiceRecords (dumpsys activity services)
9438 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009439 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009440 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009441 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009442
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009443 ItemMatcher matcher = new ItemMatcher();
9444 matcher.build(args, opti);
9445
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009446 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009447 try {
9448 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9449 for (UserInfo user : users) {
9450 if (mServiceMap.getAllServices(user.id).size() > 0) {
9451 boolean printed = false;
9452 long nowReal = SystemClock.elapsedRealtime();
9453 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9454 user.id).iterator();
9455 needSep = false;
9456 while (it.hasNext()) {
9457 ServiceRecord r = it.next();
9458 if (!matcher.match(r, r.name)) {
9459 continue;
9460 }
9461 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9462 continue;
9463 }
9464 if (!printed) {
9465 pw.println(" Active services:");
9466 printed = true;
9467 }
9468 if (needSep) {
9469 pw.println();
9470 }
9471 pw.print(" * ");
9472 pw.println(r);
9473 if (dumpAll) {
9474 r.dump(pw, " ");
9475 needSep = true;
9476 } else {
9477 pw.print(" app=");
9478 pw.println(r.app);
9479 pw.print(" created=");
9480 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9481 pw.print(" started=");
9482 pw.print(r.startRequested);
9483 pw.print(" connections=");
9484 pw.println(r.connections.size());
9485 if (r.connections.size() > 0) {
9486 pw.println(" Connections:");
9487 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9488 for (int i = 0; i < clist.size(); i++) {
9489 ConnectionRecord conn = clist.get(i);
9490 pw.print(" ");
9491 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009492 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009493 pw.print(" -> ");
9494 ProcessRecord proc = conn.binding.client;
9495 pw.println(proc != null ? proc.toShortString() : "null");
9496 }
9497 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009498 }
9499 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009500 if (dumpClient && r.app != null && r.app.thread != null) {
9501 pw.println(" Client:");
9502 pw.flush();
9503 try {
9504 TransferPipe tp = new TransferPipe();
9505 try {
9506 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9507 r, args);
9508 tp.setBufferPrefix(" ");
9509 // Short timeout, since blocking here can
9510 // deadlock with the application.
9511 tp.go(fd, 2000);
9512 } finally {
9513 tp.kill();
9514 }
9515 } catch (IOException e) {
9516 pw.println(" Failure while dumping the service: " + e);
9517 } catch (RemoteException e) {
9518 pw.println(" Got a RemoteException while dumping the service");
9519 }
9520 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009521 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009522 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009523 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009525 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009526 } catch (RemoteException re) {
9527
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009529
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009530 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009531 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009532 for (int i=0; i<mPendingServices.size(); i++) {
9533 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009534 if (!matcher.match(r, r.name)) {
9535 continue;
9536 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009537 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9538 continue;
9539 }
9540 if (!printed) {
9541 if (needSep) pw.println(" ");
9542 needSep = true;
9543 pw.println(" Pending services:");
9544 printed = true;
9545 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009546 pw.print(" * Pending "); pw.println(r);
9547 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009549 needSep = true;
9550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009551
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009552 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009553 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009554 for (int i=0; i<mRestartingServices.size(); i++) {
9555 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009556 if (!matcher.match(r, r.name)) {
9557 continue;
9558 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009559 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9560 continue;
9561 }
9562 if (!printed) {
9563 if (needSep) pw.println(" ");
9564 needSep = true;
9565 pw.println(" Restarting services:");
9566 printed = true;
9567 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009568 pw.print(" * Restarting "); pw.println(r);
9569 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009571 needSep = true;
9572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009574 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009575 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009576 for (int i=0; i<mStoppingServices.size(); i++) {
9577 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009578 if (!matcher.match(r, r.name)) {
9579 continue;
9580 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009581 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9582 continue;
9583 }
9584 if (!printed) {
9585 if (needSep) pw.println(" ");
9586 needSep = true;
9587 pw.println(" Stopping services:");
9588 printed = true;
9589 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009590 pw.print(" * Stopping "); pw.println(r);
9591 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009593 needSep = true;
9594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009595
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009596 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009598 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009599 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009600 = mServiceConnections.values().iterator();
9601 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009602 ArrayList<ConnectionRecord> r = it.next();
9603 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009604 ConnectionRecord cr = r.get(i);
9605 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9606 continue;
9607 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009608 if (dumpPackage != null && (cr.binding.client == null
9609 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9610 continue;
9611 }
9612 if (!printed) {
9613 if (needSep) pw.println(" ");
9614 needSep = true;
9615 pw.println(" Connection bindings to services:");
9616 printed = true;
9617 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009618 pw.print(" * "); pw.println(cr);
9619 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009621 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009622 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009623 }
9624 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009625
9626 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009627 }
9628
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009629 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009630 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009631 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009632
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009633 ItemMatcher matcher = new ItemMatcher();
9634 matcher.build(args, opti);
9635
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009636 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009637
9638 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009639
9640 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009641 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009642 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009643 ContentProviderRecord r = mLaunchingProviders.get(i);
9644 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9645 continue;
9646 }
9647 if (!printed) {
9648 if (needSep) pw.println(" ");
9649 needSep = true;
9650 pw.println(" Launching content providers:");
9651 printed = true;
9652 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009653 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009654 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009655 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009656 }
9657
9658 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009659 if (needSep) pw.println();
9660 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009661 pw.println("Granted Uri Permissions:");
9662 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9663 int uid = mGrantedUriPermissions.keyAt(i);
9664 HashMap<Uri, UriPermission> perms
9665 = mGrantedUriPermissions.valueAt(i);
9666 pw.print(" * UID "); pw.print(uid);
9667 pw.println(" holds:");
9668 for (UriPermission perm : perms.values()) {
9669 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009670 if (dumpAll) {
9671 perm.dump(pw, " ");
9672 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009673 }
9674 }
9675 needSep = true;
9676 }
9677
9678 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 }
9680
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009681 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009682 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009683 boolean needSep = false;
9684
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 if (mIntentSenderRecords.size() > 0) {
9686 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009687 Iterator<WeakReference<PendingIntentRecord>> it
9688 = mIntentSenderRecords.values().iterator();
9689 while (it.hasNext()) {
9690 WeakReference<PendingIntentRecord> ref = it.next();
9691 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009692 if (dumpPackage != null && (rec == null
9693 || !dumpPackage.equals(rec.key.packageName))) {
9694 continue;
9695 }
9696 if (!printed) {
9697 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9698 printed = true;
9699 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009700 needSep = true;
9701 if (rec != null) {
9702 pw.print(" * "); pw.println(rec);
9703 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009704 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009705 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009706 } else {
9707 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009708 }
9709 }
9710 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009711
9712 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009713 }
9714
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009715 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009716 String prefix, String label, boolean complete, boolean brief, boolean client,
9717 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009719 boolean needNL = false;
9720 final String innerPrefix = prefix + " ";
9721 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009722 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009723 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009724 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9725 continue;
9726 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009727 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009728 if (needNL) {
9729 pw.println(" ");
9730 needNL = false;
9731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 if (lastTask != r.task) {
9733 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009734 pw.print(prefix);
9735 pw.print(full ? "* " : " ");
9736 pw.println(lastTask);
9737 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009738 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009739 } else if (complete) {
9740 // Complete + brief == give a summary. Isn't that obvious?!?
9741 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009742 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009743 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009744 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009747 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9748 pw.print(" #"); pw.print(i); pw.print(": ");
9749 pw.println(r);
9750 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009751 r.dump(pw, innerPrefix);
9752 } else if (complete) {
9753 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009754 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009755 if (r.app != null) {
9756 pw.print(innerPrefix); pw.println(r.app);
9757 }
9758 }
9759 if (client && r.app != null && r.app.thread != null) {
9760 // flush anything that is already in the PrintWriter since the thread is going
9761 // to write to the file descriptor directly
9762 pw.flush();
9763 try {
9764 TransferPipe tp = new TransferPipe();
9765 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009766 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9767 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009768 // Short timeout, since blocking here can
9769 // deadlock with the application.
9770 tp.go(fd, 2000);
9771 } finally {
9772 tp.kill();
9773 }
9774 } catch (IOException e) {
9775 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9776 } catch (RemoteException e) {
9777 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9778 }
9779 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009781 }
9782 }
9783
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009784 private static String buildOomTag(String prefix, String space, int val, int base) {
9785 if (val == base) {
9786 if (space == null) return prefix;
9787 return prefix + " ";
9788 }
9789 return prefix + "+" + Integer.toString(val-base);
9790 }
9791
9792 private static final int dumpProcessList(PrintWriter pw,
9793 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009794 String prefix, String normalLabel, String persistentLabel,
9795 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009796 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009797 final int N = list.size()-1;
9798 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009799 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009800 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9801 continue;
9802 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009803 pw.println(String.format("%s%s #%2d: %s",
9804 prefix, (r.persistent ? persistentLabel : normalLabel),
9805 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009806 if (r.persistent) {
9807 numPers++;
9808 }
9809 }
9810 return numPers;
9811 }
9812
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009813 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009814 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009815 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009816 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009817
Dianne Hackborn905577f2011-09-07 18:31:28 -07009818 ArrayList<Pair<ProcessRecord, Integer>> list
9819 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9820 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009821 ProcessRecord r = origList.get(i);
9822 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9823 continue;
9824 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009825 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9826 }
9827
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009828 if (list.size() <= 0) {
9829 return false;
9830 }
9831
Dianne Hackborn905577f2011-09-07 18:31:28 -07009832 Comparator<Pair<ProcessRecord, Integer>> comparator
9833 = new Comparator<Pair<ProcessRecord, Integer>>() {
9834 @Override
9835 public int compare(Pair<ProcessRecord, Integer> object1,
9836 Pair<ProcessRecord, Integer> object2) {
9837 if (object1.first.setAdj != object2.first.setAdj) {
9838 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9839 }
9840 if (object1.second.intValue() != object2.second.intValue()) {
9841 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9842 }
9843 return 0;
9844 }
9845 };
9846
9847 Collections.sort(list, comparator);
9848
Dianne Hackborn287952c2010-09-22 22:34:31 -07009849 final long curRealtime = SystemClock.elapsedRealtime();
9850 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9851 final long curUptime = SystemClock.uptimeMillis();
9852 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9853
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009854 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009855 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009856 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009857 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009858 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009859 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9860 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009861 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9862 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009863 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9864 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009865 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9866 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009867 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009868 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009869 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9870 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9871 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9872 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9873 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9874 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9875 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9876 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009877 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9878 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009879 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9880 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009881 } else {
9882 oomAdj = Integer.toString(r.setAdj);
9883 }
9884 String schedGroup;
9885 switch (r.setSchedGroup) {
9886 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9887 schedGroup = "B";
9888 break;
9889 case Process.THREAD_GROUP_DEFAULT:
9890 schedGroup = "F";
9891 break;
9892 default:
9893 schedGroup = Integer.toString(r.setSchedGroup);
9894 break;
9895 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009896 String foreground;
9897 if (r.foregroundActivities) {
9898 foreground = "A";
9899 } else if (r.foregroundServices) {
9900 foreground = "S";
9901 } else {
9902 foreground = " ";
9903 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009904 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009905 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009906 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9907 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009908 if (r.adjSource != null || r.adjTarget != null) {
9909 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009910 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009911 if (r.adjTarget instanceof ComponentName) {
9912 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9913 } else if (r.adjTarget != null) {
9914 pw.print(r.adjTarget.toString());
9915 } else {
9916 pw.print("{null}");
9917 }
9918 pw.print("<=");
9919 if (r.adjSource instanceof ProcessRecord) {
9920 pw.print("Proc{");
9921 pw.print(((ProcessRecord)r.adjSource).toShortString());
9922 pw.println("}");
9923 } else if (r.adjSource != null) {
9924 pw.println(r.adjSource.toString());
9925 } else {
9926 pw.println("{null}");
9927 }
9928 }
9929 if (inclDetails) {
9930 pw.print(prefix);
9931 pw.print(" ");
9932 pw.print("oom: max="); pw.print(r.maxAdj);
9933 pw.print(" hidden="); pw.print(r.hiddenAdj);
9934 pw.print(" curRaw="); pw.print(r.curRawAdj);
9935 pw.print(" setRaw="); pw.print(r.setRawAdj);
9936 pw.print(" cur="); pw.print(r.curAdj);
9937 pw.print(" set="); pw.println(r.setAdj);
9938 pw.print(prefix);
9939 pw.print(" ");
9940 pw.print("keeping="); pw.print(r.keeping);
9941 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009942 pw.print(" empty="); pw.print(r.empty);
9943 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009944
9945 if (!r.keeping) {
9946 if (r.lastWakeTime != 0) {
9947 long wtime;
9948 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9949 synchronized (stats) {
9950 wtime = stats.getProcessWakeTime(r.info.uid,
9951 r.pid, curRealtime);
9952 }
9953 long timeUsed = wtime - r.lastWakeTime;
9954 pw.print(prefix);
9955 pw.print(" ");
9956 pw.print("keep awake over ");
9957 TimeUtils.formatDuration(realtimeSince, pw);
9958 pw.print(" used ");
9959 TimeUtils.formatDuration(timeUsed, pw);
9960 pw.print(" (");
9961 pw.print((timeUsed*100)/realtimeSince);
9962 pw.println("%)");
9963 }
9964 if (r.lastCpuTime != 0) {
9965 long timeUsed = r.curCpuTime - r.lastCpuTime;
9966 pw.print(prefix);
9967 pw.print(" ");
9968 pw.print("run cpu over ");
9969 TimeUtils.formatDuration(uptimeSince, pw);
9970 pw.print(" used ");
9971 TimeUtils.formatDuration(timeUsed, pw);
9972 pw.print(" (");
9973 pw.print((timeUsed*100)/uptimeSince);
9974 pw.println("%)");
9975 }
9976 }
9977 }
9978 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009979 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009980 }
9981
Dianne Hackbornb437e092011-08-05 17:50:29 -07009982 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009983 ArrayList<ProcessRecord> procs;
9984 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009985 if (args != null && args.length > start
9986 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009987 procs = new ArrayList<ProcessRecord>();
9988 int pid = -1;
9989 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009990 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009991 } catch (NumberFormatException e) {
9992
9993 }
9994 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9995 ProcessRecord proc = mLruProcesses.get(i);
9996 if (proc.pid == pid) {
9997 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009998 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009999 procs.add(proc);
10000 }
10001 }
10002 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010003 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010004 return null;
10005 }
10006 } else {
10007 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10008 }
10009 }
10010 return procs;
10011 }
10012
10013 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10014 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010015 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010016 if (procs == null) {
10017 return;
10018 }
10019
10020 long uptime = SystemClock.uptimeMillis();
10021 long realtime = SystemClock.elapsedRealtime();
10022 pw.println("Applications Graphics Acceleration Info:");
10023 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10024
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010025 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10026 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010027 if (r.thread != null) {
10028 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10029 pw.flush();
10030 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010031 TransferPipe tp = new TransferPipe();
10032 try {
10033 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10034 tp.go(fd);
10035 } finally {
10036 tp.kill();
10037 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010038 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010039 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010040 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010041 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010042 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010043 pw.flush();
10044 }
10045 }
10046 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010047 }
10048
Jeff Brown6754ba22011-12-14 20:20:01 -080010049 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10050 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10051 if (procs == null) {
10052 return;
10053 }
10054
10055 pw.println("Applications Database Info:");
10056
10057 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10058 ProcessRecord r = procs.get(i);
10059 if (r.thread != null) {
10060 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10061 pw.flush();
10062 try {
10063 TransferPipe tp = new TransferPipe();
10064 try {
10065 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10066 tp.go(fd);
10067 } finally {
10068 tp.kill();
10069 }
10070 } catch (IOException e) {
10071 pw.println("Failure while dumping the app: " + r);
10072 pw.flush();
10073 } catch (RemoteException e) {
10074 pw.println("Got a RemoteException while dumping the app " + r);
10075 pw.flush();
10076 }
10077 }
10078 }
10079 }
10080
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010081 final static class MemItem {
10082 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010083 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010084 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010085 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010086 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010087
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010088 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010089 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010090 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010091 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010092 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010093 }
10094 }
10095
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010096 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010097 boolean sort) {
10098 if (sort) {
10099 Collections.sort(items, new Comparator<MemItem>() {
10100 @Override
10101 public int compare(MemItem lhs, MemItem rhs) {
10102 if (lhs.pss < rhs.pss) {
10103 return 1;
10104 } else if (lhs.pss > rhs.pss) {
10105 return -1;
10106 }
10107 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010108 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010109 });
10110 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010111
10112 for (int i=0; i<items.size(); i++) {
10113 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010114 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010115 if (mi.subitems != null) {
10116 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10117 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010118 }
10119 }
10120
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010121 // These are in KB.
10122 static final long[] DUMP_MEM_BUCKETS = new long[] {
10123 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10124 120*1024, 160*1024, 200*1024,
10125 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10126 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10127 };
10128
Dianne Hackborn672342c2011-11-29 11:29:02 -080010129 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10130 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010131 int start = label.lastIndexOf('.');
10132 if (start >= 0) start++;
10133 else start = 0;
10134 int end = label.length();
10135 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10136 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10137 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10138 out.append(bucket);
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 return;
10142 }
10143 }
10144 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010145 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010146 out.append(label, start, end);
10147 }
10148
10149 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10150 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10151 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10152 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10153 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10154 };
10155 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10156 "System", "Persistent", "Foreground",
10157 "Visible", "Perceptible", "Heavy Weight",
10158 "Backup", "A Services", "Home", "Previous",
10159 "B Services", "Background"
10160 };
10161
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010162 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010163 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010164 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010165 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010166 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010167
10168 int opti = 0;
10169 while (opti < args.length) {
10170 String opt = args[opti];
10171 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10172 break;
10173 }
10174 opti++;
10175 if ("-a".equals(opt)) {
10176 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010177 } else if ("--oom".equals(opt)) {
10178 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010179 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010180 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010181 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010182 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010183 pw.println("If [process] is specified it can be the name or ");
10184 pw.println("pid of a specific process to dump.");
10185 return;
10186 } else {
10187 pw.println("Unknown argument: " + opt + "; use -h for help");
10188 }
10189 }
10190
10191 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010192 if (procs == null) {
10193 return;
10194 }
10195
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010196 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010197 long uptime = SystemClock.uptimeMillis();
10198 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010199
10200 if (procs.size() == 1 || isCheckinRequest) {
10201 dumpAll = true;
10202 }
10203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010204 if (isCheckinRequest) {
10205 // short checkin version
10206 pw.println(uptime + "," + realtime);
10207 pw.flush();
10208 } else {
10209 pw.println("Applications Memory Usage (kB):");
10210 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10211 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010212
Dianne Hackbornb437e092011-08-05 17:50:29 -070010213 String[] innerArgs = new String[args.length-opti];
10214 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10215
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010216 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10217 long nativePss=0, dalvikPss=0, otherPss=0;
10218 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10219
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010220 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10221 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10222 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010223
10224 long totalPss = 0;
10225
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010226 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10227 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010229 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10231 pw.flush();
10232 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010233 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010234 if (dumpAll) {
10235 try {
10236 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10237 } catch (RemoteException e) {
10238 if (!isCheckinRequest) {
10239 pw.println("Got RemoteException!");
10240 pw.flush();
10241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010243 } else {
10244 mi = new Debug.MemoryInfo();
10245 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010246 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010247
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010248 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010249 long myTotalPss = mi.getTotalPss();
10250 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010251 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010252 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010253 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010254
10255 nativePss += mi.nativePss;
10256 dalvikPss += mi.dalvikPss;
10257 otherPss += mi.otherPss;
10258 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10259 long mem = mi.getOtherPss(j);
10260 miscPss[j] += mem;
10261 otherPss -= mem;
10262 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010263
10264 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010265 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10266 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010267 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010268 if (oomProcs[oomIndex] == null) {
10269 oomProcs[oomIndex] = new ArrayList<MemItem>();
10270 }
10271 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010272 break;
10273 }
10274 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010276 }
10277 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010278
10279 if (!isCheckinRequest && procs.size() > 1) {
10280 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10281
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010282 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10283 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10284 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010285 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010286 String label = Debug.MemoryInfo.getOtherLabel(j);
10287 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010288 }
10289
Dianne Hackbornb437e092011-08-05 17:50:29 -070010290 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10291 for (int j=0; j<oomPss.length; j++) {
10292 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010293 String label = DUMP_MEM_OOM_LABEL[j];
10294 MemItem item = new MemItem(label, label, oomPss[j],
10295 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010296 item.subitems = oomProcs[j];
10297 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010298 }
10299 }
10300
Dianne Hackborn672342c2011-11-29 11:29:02 -080010301 if (outTag != null || outStack != null) {
10302 if (outTag != null) {
10303 appendMemBucket(outTag, totalPss, "total", false);
10304 }
10305 if (outStack != null) {
10306 appendMemBucket(outStack, totalPss, "total", true);
10307 }
10308 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010309 for (int i=0; i<oomMems.size(); i++) {
10310 MemItem miCat = oomMems.get(i);
10311 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10312 continue;
10313 }
10314 if (miCat.id < ProcessList.SERVICE_ADJ
10315 || miCat.id == ProcessList.HOME_APP_ADJ
10316 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010317 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10318 outTag.append(" / ");
10319 }
10320 if (outStack != null) {
10321 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10322 if (firstLine) {
10323 outStack.append(":");
10324 firstLine = false;
10325 }
10326 outStack.append("\n\t at ");
10327 } else {
10328 outStack.append("$");
10329 }
10330 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010331 for (int j=0; j<miCat.subitems.size(); j++) {
10332 MemItem mi = miCat.subitems.get(j);
10333 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010334 if (outTag != null) {
10335 outTag.append(" ");
10336 }
10337 if (outStack != null) {
10338 outStack.append("$");
10339 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010340 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010341 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10342 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10343 }
10344 if (outStack != null) {
10345 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10346 }
10347 }
10348 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10349 outStack.append("(");
10350 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10351 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10352 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10353 outStack.append(":");
10354 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10355 }
10356 }
10357 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010358 }
10359 }
10360 }
10361 }
10362
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010363 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010364 pw.println();
10365 pw.println("Total PSS by process:");
10366 dumpMemItems(pw, " ", procMems, true);
10367 pw.println();
10368 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010369 pw.println("Total PSS by OOM adjustment:");
10370 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010371 if (!oomOnly) {
10372 PrintWriter out = categoryPw != null ? categoryPw : pw;
10373 out.println();
10374 out.println("Total PSS by category:");
10375 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010376 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010377 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010378 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010379 final int[] SINGLE_LONG_FORMAT = new int[] {
10380 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10381 };
10382 long[] longOut = new long[1];
10383 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10384 SINGLE_LONG_FORMAT, null, longOut, null);
10385 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10386 longOut[0] = 0;
10387 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10388 SINGLE_LONG_FORMAT, null, longOut, null);
10389 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10390 longOut[0] = 0;
10391 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10392 SINGLE_LONG_FORMAT, null, longOut, null);
10393 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10394 longOut[0] = 0;
10395 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10396 SINGLE_LONG_FORMAT, null, longOut, null);
10397 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10398 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10399 pw.print(shared); pw.println(" kB");
10400 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10401 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010403 }
10404
10405 /**
10406 * Searches array of arguments for the specified string
10407 * @param args array of argument strings
10408 * @param value value to search for
10409 * @return true if the value is contained in the array
10410 */
10411 private static boolean scanArgs(String[] args, String value) {
10412 if (args != null) {
10413 for (String arg : args) {
10414 if (value.equals(arg)) {
10415 return true;
10416 }
10417 }
10418 }
10419 return false;
10420 }
10421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010422 private final void killServicesLocked(ProcessRecord app,
10423 boolean allowRestart) {
10424 // Report disconnected services.
10425 if (false) {
10426 // XXX we are letting the client link to the service for
10427 // death notifications.
10428 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010429 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010431 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010432 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010433 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010434 = r.connections.values().iterator();
10435 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010436 ArrayList<ConnectionRecord> cl = jt.next();
10437 for (int i=0; i<cl.size(); i++) {
10438 ConnectionRecord c = cl.get(i);
10439 if (c.binding.client != app) {
10440 try {
10441 //c.conn.connected(r.className, null);
10442 } catch (Exception e) {
10443 // todo: this should be asynchronous!
10444 Slog.w(TAG, "Exception thrown disconnected servce "
10445 + r.shortName
10446 + " from app " + app.processName, e);
10447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010448 }
10449 }
10450 }
10451 }
10452 }
10453 }
10454 }
10455
10456 // Clean up any connections this application has to other services.
10457 if (app.connections.size() > 0) {
10458 Iterator<ConnectionRecord> it = app.connections.iterator();
10459 while (it.hasNext()) {
10460 ConnectionRecord r = it.next();
10461 removeConnectionLocked(r, app, null);
10462 }
10463 }
10464 app.connections.clear();
10465
10466 if (app.services.size() != 0) {
10467 // Any services running in the application need to be placed
10468 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010469 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010470 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010471 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472 synchronized (sr.stats.getBatteryStats()) {
10473 sr.stats.stopLaunchedLocked();
10474 }
10475 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010476 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010477 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010478 if (mStoppingServices.remove(sr)) {
10479 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10480 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010481
10482 boolean hasClients = sr.bindings.size() > 0;
10483 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 Iterator<IntentBindRecord> bindings
10485 = sr.bindings.values().iterator();
10486 while (bindings.hasNext()) {
10487 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010488 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010489 + ": shouldUnbind=" + b.hasBound);
10490 b.binder = null;
10491 b.requested = b.received = b.hasBound = false;
10492 }
10493 }
10494
Dianne Hackborn070783f2010-12-29 16:46:28 -080010495 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10496 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010497 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010499 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010500 sr.crashCount, sr.shortName, app.pid);
10501 bringDownServiceLocked(sr, true);
10502 } else if (!allowRestart) {
10503 bringDownServiceLocked(sr, true);
10504 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010505 boolean canceled = scheduleServiceRestartLocked(sr, true);
10506
10507 // Should the service remain running? Note that in the
10508 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010509 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010510 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10511 if (sr.pendingStarts.size() == 0) {
10512 sr.startRequested = false;
10513 if (!hasClients) {
10514 // Whoops, no reason to restart!
10515 bringDownServiceLocked(sr, true);
10516 }
10517 }
10518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010519 }
10520 }
10521
10522 if (!allowRestart) {
10523 app.services.clear();
10524 }
10525 }
10526
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010527 // Make sure we have no more records on the stopping list.
10528 int i = mStoppingServices.size();
10529 while (i > 0) {
10530 i--;
10531 ServiceRecord sr = mStoppingServices.get(i);
10532 if (sr.app == app) {
10533 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010534 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010535 }
10536 }
10537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010538 app.executingServices.clear();
10539 }
10540
10541 private final void removeDyingProviderLocked(ProcessRecord proc,
10542 ContentProviderRecord cpr) {
10543 synchronized (cpr) {
10544 cpr.launchingApp = null;
10545 cpr.notifyAll();
10546 }
10547
Amith Yamasani742a6712011-05-04 14:49:28 -070010548 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010549 String names[] = cpr.info.authority.split(";");
10550 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010551 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010552 }
10553
10554 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10555 while (cit.hasNext()) {
10556 ProcessRecord capp = cit.next();
10557 if (!capp.persistent && capp.thread != null
10558 && capp.pid != 0
10559 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010560 Slog.i(TAG, "Kill " + capp.processName
10561 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010562 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010563 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010564 capp.processName, capp.setAdj, "dying provider "
10565 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010566 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 }
10568 }
10569
10570 mLaunchingProviders.remove(cpr);
10571 }
10572
10573 /**
10574 * Main code for cleaning up a process when it has gone away. This is
10575 * called both as a result of the process dying, or directly when stopping
10576 * a process when running in single process mode.
10577 */
10578 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010579 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010581 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 }
10583
Dianne Hackborn36124872009-10-08 16:22:03 -070010584 mProcessesToGc.remove(app);
10585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 // Dismiss any open dialogs.
10587 if (app.crashDialog != null) {
10588 app.crashDialog.dismiss();
10589 app.crashDialog = null;
10590 }
10591 if (app.anrDialog != null) {
10592 app.anrDialog.dismiss();
10593 app.anrDialog = null;
10594 }
10595 if (app.waitDialog != null) {
10596 app.waitDialog.dismiss();
10597 app.waitDialog = null;
10598 }
10599
10600 app.crashing = false;
10601 app.notResponding = false;
10602
10603 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010604 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 app.thread = null;
10606 app.forcingToForeground = null;
10607 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010608 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010609 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010610 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010612 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613
10614 boolean restart = false;
10615
10616 int NL = mLaunchingProviders.size();
10617
10618 // Remove published content providers.
10619 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010620 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010621 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010622 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010623 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010624 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625
10626 // See if someone is waiting for this provider... in which
10627 // case we don't remove it, but just let it restart.
10628 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010629 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 for (; i<NL; i++) {
10631 if (mLaunchingProviders.get(i) == cpr) {
10632 restart = true;
10633 break;
10634 }
10635 }
10636 } else {
10637 i = NL;
10638 }
10639
10640 if (i >= NL) {
10641 removeDyingProviderLocked(app, cpr);
10642 NL = mLaunchingProviders.size();
10643 }
10644 }
10645 app.pubProviders.clear();
10646 }
10647
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010648 // Take care of any launching providers waiting for this process.
10649 if (checkAppInLaunchingProvidersLocked(app, false)) {
10650 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010651 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 // Unregister from connected content providers.
10654 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010655 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010656 while (it.hasNext()) {
10657 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10658 cpr.clients.remove(app);
10659 }
10660 app.conProviders.clear();
10661 }
10662
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010663 // At this point there may be remaining entries in mLaunchingProviders
10664 // where we were the only one waiting, so they are no longer of use.
10665 // Look for these and clean up if found.
10666 // XXX Commented out for now. Trying to figure out a way to reproduce
10667 // the actual situation to identify what is actually going on.
10668 if (false) {
10669 for (int i=0; i<NL; i++) {
10670 ContentProviderRecord cpr = (ContentProviderRecord)
10671 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010672 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010673 synchronized (cpr) {
10674 cpr.launchingApp = null;
10675 cpr.notifyAll();
10676 }
10677 }
10678 }
10679 }
10680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 skipCurrentReceiverLocked(app);
10682
10683 // Unregister any receivers.
10684 if (app.receivers.size() > 0) {
10685 Iterator<ReceiverList> it = app.receivers.iterator();
10686 while (it.hasNext()) {
10687 removeReceiverLocked(it.next());
10688 }
10689 app.receivers.clear();
10690 }
10691
Christopher Tate181fafa2009-05-14 11:12:14 -070010692 // If the app is undergoing backup, tell the backup manager about it
10693 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010694 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010695 try {
10696 IBackupManager bm = IBackupManager.Stub.asInterface(
10697 ServiceManager.getService(Context.BACKUP_SERVICE));
10698 bm.agentDisconnected(app.info.packageName);
10699 } catch (RemoteException e) {
10700 // can't happen; backup manager is local
10701 }
10702 }
10703
Jeff Sharkey287bd832011-05-28 19:36:26 -070010704 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010706 // If the caller is restarting this app, then leave it in its
10707 // current lists and let the caller take care of it.
10708 if (restarting) {
10709 return;
10710 }
10711
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010712 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010713 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010714 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010715 mProcessNames.remove(app.processName, app.uid);
10716 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010717 if (mHeavyWeightProcess == app) {
10718 mHeavyWeightProcess = null;
10719 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010721 } else if (!app.removed) {
10722 // This app is persistent, so we need to keep its record around.
10723 // If it is not already on the pending app list, add it there
10724 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010725 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10726 mPersistentStartingProcesses.add(app);
10727 restart = true;
10728 }
10729 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010730 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10731 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010732 mProcessesOnHold.remove(app);
10733
The Android Open Source Project4df24232009-03-05 14:34:35 -080010734 if (app == mHomeProcess) {
10735 mHomeProcess = null;
10736 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010737 if (app == mPreviousProcess) {
10738 mPreviousProcess = null;
10739 }
10740
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010741 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 // We have components that still need to be running in the
10743 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010744 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010745 startProcessLocked(app, "restart", app.processName);
10746 } else if (app.pid > 0 && app.pid != MY_PID) {
10747 // Goodbye!
10748 synchronized (mPidsSelfLocked) {
10749 mPidsSelfLocked.remove(app.pid);
10750 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10751 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010752 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 }
10754 }
10755
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010756 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10757 // Look through the content providers we are waiting to have launched,
10758 // and if any run in this process then either schedule a restart of
10759 // the process or kill the client waiting for it if this process has
10760 // gone bad.
10761 int NL = mLaunchingProviders.size();
10762 boolean restart = false;
10763 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010764 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010765 if (cpr.launchingApp == app) {
10766 if (!alwaysBad && !app.bad) {
10767 restart = true;
10768 } else {
10769 removeDyingProviderLocked(app, cpr);
10770 NL = mLaunchingProviders.size();
10771 }
10772 }
10773 }
10774 return restart;
10775 }
10776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 // =========================================================
10778 // SERVICES
10779 // =========================================================
10780
10781 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10782 ActivityManager.RunningServiceInfo info =
10783 new ActivityManager.RunningServiceInfo();
10784 info.service = r.name;
10785 if (r.app != null) {
10786 info.pid = r.app.pid;
10787 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010788 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 info.process = r.processName;
10790 info.foreground = r.isForeground;
10791 info.activeSince = r.createTime;
10792 info.started = r.startRequested;
10793 info.clientCount = r.connections.size();
10794 info.crashCount = r.crashCount;
10795 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010796 if (r.isForeground) {
10797 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10798 }
10799 if (r.startRequested) {
10800 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10801 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010802 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010803 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10804 }
10805 if (r.app != null && r.app.persistent) {
10806 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10807 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010808
10809 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10810 for (int i=0; i<connl.size(); i++) {
10811 ConnectionRecord conn = connl.get(i);
10812 if (conn.clientLabel != 0) {
10813 info.clientPackage = conn.binding.client.info.packageName;
10814 info.clientLabel = conn.clientLabel;
10815 return info;
10816 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010817 }
10818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 return info;
10820 }
10821
10822 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10823 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010824 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 synchronized (this) {
10826 ArrayList<ActivityManager.RunningServiceInfo> res
10827 = new ArrayList<ActivityManager.RunningServiceInfo>();
10828
Amith Yamasani742a6712011-05-04 14:49:28 -070010829 int userId = UserId.getUserId(Binder.getCallingUid());
10830 if (mServiceMap.getAllServices(userId).size() > 0) {
10831 Iterator<ServiceRecord> it
10832 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 while (it.hasNext() && res.size() < maxNum) {
10834 res.add(makeRunningServiceInfoLocked(it.next()));
10835 }
10836 }
10837
10838 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10839 ServiceRecord r = mRestartingServices.get(i);
10840 ActivityManager.RunningServiceInfo info =
10841 makeRunningServiceInfoLocked(r);
10842 info.restarting = r.nextRestartTime;
10843 res.add(info);
10844 }
10845
10846 return res;
10847 }
10848 }
10849
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010850 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010851 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010852 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010853 int userId = UserId.getUserId(Binder.getCallingUid());
10854 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010855 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010856 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10857 for (int i=0; i<conn.size(); i++) {
10858 if (conn.get(i).clientIntent != null) {
10859 return conn.get(i).clientIntent;
10860 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010861 }
10862 }
10863 }
10864 }
10865 return null;
10866 }
10867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 private final ServiceRecord findServiceLocked(ComponentName name,
10869 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010870 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 return r == token ? r : null;
10872 }
10873
10874 private final class ServiceLookupResult {
10875 final ServiceRecord record;
10876 final String permission;
10877
10878 ServiceLookupResult(ServiceRecord _record, String _permission) {
10879 record = _record;
10880 permission = _permission;
10881 }
10882 };
10883
10884 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010885 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 ServiceRecord r = null;
10887 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010888 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010889 }
10890 if (r == null) {
10891 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010892 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 }
10894
10895 if (r == null) {
10896 try {
10897 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010898 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010899 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 ServiceInfo sInfo =
10901 rInfo != null ? rInfo.serviceInfo : null;
10902 if (sInfo == null) {
10903 return null;
10904 }
10905
10906 ComponentName name = new ComponentName(
10907 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010908 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 } catch (RemoteException ex) {
10910 // pm is in same process, this will never happen.
10911 }
10912 }
10913 if (r != null) {
10914 int callingPid = Binder.getCallingPid();
10915 int callingUid = Binder.getCallingUid();
10916 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010917 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010918 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010919 if (!r.exported) {
10920 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10921 + " from pid=" + callingPid
10922 + ", uid=" + callingUid
10923 + " that is not exported from uid " + r.appInfo.uid);
10924 return new ServiceLookupResult(null, "not exported from uid "
10925 + r.appInfo.uid);
10926 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010927 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 + " from pid=" + callingPid
10929 + ", uid=" + callingUid
10930 + " requires " + r.permission);
10931 return new ServiceLookupResult(null, r.permission);
10932 }
10933 return new ServiceLookupResult(r, null);
10934 }
10935 return null;
10936 }
10937
10938 private class ServiceRestarter implements Runnable {
10939 private ServiceRecord mService;
10940
10941 void setService(ServiceRecord service) {
10942 mService = service;
10943 }
10944
10945 public void run() {
10946 synchronized(ActivityManagerService.this) {
10947 performServiceRestartLocked(mService);
10948 }
10949 }
10950 }
10951
10952 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010953 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010955 if (DEBUG_SERVICE)
10956 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010957 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010960 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010961 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010962 if (r == null) {
10963 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010964 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 if (r == null) {
10967 try {
10968 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010969 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010970 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 ServiceInfo sInfo =
10972 rInfo != null ? rInfo.serviceInfo : null;
10973 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010974 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010975 ": not found");
10976 return null;
10977 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010978 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010979 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
10980 userId = 0;
10981 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010982 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 ComponentName name = new ComponentName(
10985 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010986 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010988 Intent.FilterComparison filter = new Intent.FilterComparison(
10989 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990 ServiceRestarter res = new ServiceRestarter();
10991 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10992 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10993 synchronized (stats) {
10994 ss = stats.getServiceStatsLocked(
10995 sInfo.applicationInfo.uid, sInfo.packageName,
10996 sInfo.name);
10997 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010998 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011000 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11001 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011002
11003 // Make sure this component isn't in the pending list.
11004 int N = mPendingServices.size();
11005 for (int i=0; i<N; i++) {
11006 ServiceRecord pr = mPendingServices.get(i);
11007 if (pr.name.equals(name)) {
11008 mPendingServices.remove(i);
11009 i--;
11010 N--;
11011 }
11012 }
11013 }
11014 } catch (RemoteException ex) {
11015 // pm is in same process, this will never happen.
11016 }
11017 }
11018 if (r != null) {
11019 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011020 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011022 if (!r.exported) {
11023 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11024 + " from pid=" + callingPid
11025 + ", uid=" + callingUid
11026 + " that is not exported from uid " + r.appInfo.uid);
11027 return new ServiceLookupResult(null, "not exported from uid "
11028 + r.appInfo.uid);
11029 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011030 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011031 + " from pid=" + callingPid
11032 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011033 + " requires " + r.permission);
11034 return new ServiceLookupResult(null, r.permission);
11035 }
11036 return new ServiceLookupResult(r, null);
11037 }
11038 return null;
11039 }
11040
Dianne Hackborn287952c2010-09-22 22:34:31 -070011041 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11042 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11043 + why + " of " + r + " in app " + r.app);
11044 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11045 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011046 long now = SystemClock.uptimeMillis();
11047 if (r.executeNesting == 0 && r.app != null) {
11048 if (r.app.executingServices.size() == 0) {
11049 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11050 msg.obj = r.app;
11051 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11052 }
11053 r.app.executingServices.add(r);
11054 }
11055 r.executeNesting++;
11056 r.executingStart = now;
11057 }
11058
11059 private final void sendServiceArgsLocked(ServiceRecord r,
11060 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011061 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011062 if (N == 0) {
11063 return;
11064 }
11065
Dianne Hackborn39792d22010-08-19 18:01:52 -070011066 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011067 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011068 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011069 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11070 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011071 if (si.intent == null && N > 1) {
11072 // If somehow we got a dummy null intent in the middle,
11073 // then skip it. DO NOT skip a null intent when it is
11074 // the only one in the list -- this is to support the
11075 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011076 continue;
11077 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011078 si.deliveredTime = SystemClock.uptimeMillis();
11079 r.deliveredStarts.add(si);
11080 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011081 if (si.neededGrants != null) {
11082 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11083 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011084 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011085 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011086 if (!oomAdjusted) {
11087 oomAdjusted = true;
11088 updateOomAdjLocked(r.app);
11089 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011090 int flags = 0;
Dianne Hackbornd8f10242012-05-08 17:14:58 -070011091 if (si.deliveryCount > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011092 flags |= Service.START_FLAG_RETRY;
11093 }
11094 if (si.doneExecutingCount > 0) {
11095 flags |= Service.START_FLAG_REDELIVERY;
11096 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011097 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011098 } catch (RemoteException e) {
11099 // Remote process gone... we'll let the normal cleanup take
11100 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011101 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011102 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011104 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011105 break;
11106 }
11107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011108 }
11109
11110 private final boolean requestServiceBindingLocked(ServiceRecord r,
11111 IntentBindRecord i, boolean rebind) {
11112 if (r.app == null || r.app.thread == null) {
11113 // If service is not currently running, can't yet bind.
11114 return false;
11115 }
11116 if ((!i.requested || rebind) && i.apps.size() > 0) {
11117 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011118 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011119 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11120 if (!rebind) {
11121 i.requested = true;
11122 }
11123 i.hasBound = true;
11124 i.doRebind = false;
11125 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011126 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011127 return false;
11128 }
11129 }
11130 return true;
11131 }
11132
11133 private final void requestServiceBindingsLocked(ServiceRecord r) {
11134 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11135 while (bindings.hasNext()) {
11136 IntentBindRecord i = bindings.next();
11137 if (!requestServiceBindingLocked(r, i, false)) {
11138 break;
11139 }
11140 }
11141 }
11142
11143 private final void realStartServiceLocked(ServiceRecord r,
11144 ProcessRecord app) throws RemoteException {
11145 if (app.thread == null) {
11146 throw new RemoteException();
11147 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011148 if (DEBUG_MU)
11149 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011150 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011151 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011152 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153
11154 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011155 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011156 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011157
11158 boolean created = false;
11159 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011160 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011161 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011162 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011164 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 synchronized (r.stats.getBatteryStats()) {
11166 r.stats.startLaunchedLocked();
11167 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011168 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011169 app.thread.scheduleCreateService(r, r.serviceInfo,
11170 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011171 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011172 created = true;
11173 } finally {
11174 if (!created) {
11175 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011176 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 }
11178 }
11179
11180 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011181
11182 // If the service is in the started state, and there are no
11183 // pending arguments, then fake up one so its onStartCommand() will
11184 // be called.
11185 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011186 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011187 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011188 }
11189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190 sendServiceArgsLocked(r, true);
11191 }
11192
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011193 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11194 boolean allowCancel) {
11195 boolean canceled = false;
11196
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011197 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011198 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011199 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011200
Dianne Hackborn070783f2010-12-29 16:46:28 -080011201 if ((r.serviceInfo.applicationInfo.flags
11202 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11203 minDuration /= 4;
11204 }
11205
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011206 // Any delivered but not yet finished starts should be put back
11207 // on the pending list.
11208 final int N = r.deliveredStarts.size();
11209 if (N > 0) {
11210 for (int i=N-1; i>=0; i--) {
11211 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011212 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011213 if (si.intent == null) {
11214 // We'll generate this again if needed.
11215 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11216 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11217 r.pendingStarts.add(0, si);
11218 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11219 dur *= 2;
11220 if (minDuration < dur) minDuration = dur;
11221 if (resetTime < dur) resetTime = dur;
11222 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011223 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011224 + r.name);
11225 canceled = true;
11226 }
11227 }
11228 r.deliveredStarts.clear();
11229 }
11230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231 r.totalRestartCount++;
11232 if (r.restartDelay == 0) {
11233 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011234 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 } else {
11236 // If it has been a "reasonably long time" since the service
11237 // was started, then reset our restart duration back to
11238 // the beginning, so we don't infinitely increase the duration
11239 // on a service that just occasionally gets killed (which is
11240 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011241 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011242 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011243 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011244 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011245 if ((r.serviceInfo.applicationInfo.flags
11246 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11247 // Services in peristent processes will restart much more
11248 // quickly, since they are pretty important. (Think SystemUI).
11249 r.restartDelay += minDuration/2;
11250 } else {
11251 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11252 if (r.restartDelay < minDuration) {
11253 r.restartDelay = minDuration;
11254 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 }
11257 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011258
11259 r.nextRestartTime = now + r.restartDelay;
11260
11261 // Make sure that we don't end up restarting a bunch of services
11262 // all at the same time.
11263 boolean repeat;
11264 do {
11265 repeat = false;
11266 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11267 ServiceRecord r2 = mRestartingServices.get(i);
11268 if (r2 != r && r.nextRestartTime
11269 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11270 && r.nextRestartTime
11271 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11272 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11273 r.restartDelay = r.nextRestartTime - now;
11274 repeat = true;
11275 break;
11276 }
11277 }
11278 } while (repeat);
11279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 if (!mRestartingServices.contains(r)) {
11281 mRestartingServices.add(r);
11282 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011283
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011284 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011286 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011287 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011288 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011289 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011290 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011291 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292 r.shortName, r.restartDelay);
11293
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011294 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295 }
11296
11297 final void performServiceRestartLocked(ServiceRecord r) {
11298 if (!mRestartingServices.contains(r)) {
11299 return;
11300 }
11301 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11302 }
11303
11304 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11305 if (r.restartDelay == 0) {
11306 return false;
11307 }
11308 r.resetRestartCounter();
11309 mRestartingServices.remove(r);
11310 mHandler.removeCallbacks(r.restarter);
11311 return true;
11312 }
11313
11314 private final boolean bringUpServiceLocked(ServiceRecord r,
11315 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011316 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 //r.dump(" ");
11318
Dianne Hackborn36124872009-10-08 16:22:03 -070011319 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 sendServiceArgsLocked(r, false);
11321 return true;
11322 }
11323
11324 if (!whileRestarting && r.restartDelay > 0) {
11325 // If waiting for a restart, then do nothing.
11326 return true;
11327 }
11328
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011329 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011331 // We are now bringing the service up, so no longer in the
11332 // restarting state.
11333 mRestartingServices.remove(r);
11334
Dianne Hackborne7f97212011-02-24 14:40:20 -080011335 // Service is now being launched, its package can't be stopped.
11336 try {
11337 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011338 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011339 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011340 } catch (IllegalArgumentException e) {
11341 Slog.w(TAG, "Failed trying to unstop package "
11342 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011343 }
11344
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011345 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011346 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011347 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011349 if (!isolated) {
11350 app = getProcessRecordLocked(appName, r.appInfo.uid);
11351 if (DEBUG_MU)
11352 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11353 if (app != null && app.thread != null) {
11354 try {
11355 app.addPackage(r.appInfo.packageName);
11356 realStartServiceLocked(r, app);
11357 return true;
11358 } catch (RemoteException e) {
11359 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11360 }
11361
11362 // If a dead object exception was thrown -- fall through to
11363 // restart the application.
11364 }
11365 } else {
11366 // If this service runs in an isolated process, then each time
11367 // we call startProcessLocked() we will get a new isolated
11368 // process, starting another process if we are currently waiting
11369 // for a previous process to come up. To deal with this, we store
11370 // in the service any current isolated process it is running in or
11371 // waiting to have come up.
11372 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 }
11374
Dianne Hackborn36124872009-10-08 16:22:03 -070011375 // Not running -- get it started, and enqueue this service record
11376 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011377 if (app == null) {
11378 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11379 "service", r.name, false, isolated)) == null) {
11380 Slog.w(TAG, "Unable to launch app "
11381 + r.appInfo.packageName + "/"
11382 + r.appInfo.uid + " for service "
11383 + r.intent.getIntent() + ": process is bad");
11384 bringDownServiceLocked(r, true);
11385 return false;
11386 }
11387 if (isolated) {
11388 r.isolatedProc = app;
11389 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011390 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011392 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 mPendingServices.add(r);
11394 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 return true;
11397 }
11398
11399 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011400 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 //r.dump(" ");
11402
11403 // Does it still need to run?
11404 if (!force && r.startRequested) {
11405 return;
11406 }
11407 if (r.connections.size() > 0) {
11408 if (!force) {
11409 // XXX should probably keep a count of the number of auto-create
11410 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011411 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011413 ArrayList<ConnectionRecord> cr = it.next();
11414 for (int i=0; i<cr.size(); i++) {
11415 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11416 return;
11417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 }
11419 }
11420 }
11421
11422 // Report to all of the connections that the service is no longer
11423 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011424 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011425 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011426 ArrayList<ConnectionRecord> c = it.next();
11427 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011428 ConnectionRecord cr = c.get(i);
11429 // There is still a connection to the service that is
11430 // being brought down. Mark it as dead.
11431 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011432 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011433 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011434 } catch (Exception e) {
11435 Slog.w(TAG, "Failure disconnecting service " + r.name +
11436 " to connection " + c.get(i).conn.asBinder() +
11437 " (in " + c.get(i).binding.client.processName + ")", e);
11438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011439 }
11440 }
11441 }
11442
11443 // Tell the service that it has been unbound.
11444 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11445 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11446 while (it.hasNext()) {
11447 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011448 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 + ": hasBound=" + ibr.hasBound);
11450 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11451 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011452 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 updateOomAdjLocked(r.app);
11454 ibr.hasBound = false;
11455 r.app.thread.scheduleUnbindService(r,
11456 ibr.intent.getIntent());
11457 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011458 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011459 + r.shortName, e);
11460 serviceDoneExecutingLocked(r, true);
11461 }
11462 }
11463 }
11464 }
11465
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011466 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011467 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011468 System.identityHashCode(r), r.shortName,
11469 (r.app != null) ? r.app.pid : -1);
11470
Amith Yamasani742a6712011-05-04 14:49:28 -070011471 mServiceMap.removeServiceByName(r.name, r.userId);
11472 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 r.totalRestartCount = 0;
11474 unscheduleServiceRestartLocked(r);
11475
11476 // Also make sure it is not on the pending list.
11477 int N = mPendingServices.size();
11478 for (int i=0; i<N; i++) {
11479 if (mPendingServices.get(i) == r) {
11480 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011481 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 i--;
11483 N--;
11484 }
11485 }
11486
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011487 r.cancelNotification();
11488 r.isForeground = false;
11489 r.foregroundId = 0;
11490 r.foregroundNoti = null;
11491
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011492 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011493 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011494 r.pendingStarts.clear();
11495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 if (r.app != null) {
11497 synchronized (r.stats.getBatteryStats()) {
11498 r.stats.stopLaunchedLocked();
11499 }
11500 r.app.services.remove(r);
11501 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011503 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 mStoppingServices.add(r);
11505 updateOomAdjLocked(r.app);
11506 r.app.thread.scheduleStopService(r);
11507 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011508 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011509 + r.shortName, e);
11510 serviceDoneExecutingLocked(r, true);
11511 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011512 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011513 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011514 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011515 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 }
11517 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011518 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011519 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011520 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011521
11522 if (r.bindings.size() > 0) {
11523 r.bindings.clear();
11524 }
11525
11526 if (r.restarter instanceof ServiceRestarter) {
11527 ((ServiceRestarter)r.restarter).setService(null);
11528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011529 }
11530
11531 ComponentName startServiceLocked(IApplicationThread caller,
11532 Intent service, String resolvedType,
11533 int callingPid, int callingUid) {
11534 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011535 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011536 + " type=" + resolvedType + " args=" + service.getExtras());
11537
11538 if (caller != null) {
11539 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11540 if (callerApp == null) {
11541 throw new SecurityException(
11542 "Unable to find app for caller " + caller
11543 + " (pid=" + Binder.getCallingPid()
11544 + ") when starting service " + service);
11545 }
11546 }
11547
11548 ServiceLookupResult res =
11549 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011550 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 if (res == null) {
11552 return null;
11553 }
11554 if (res.record == null) {
11555 return new ComponentName("!", res.permission != null
11556 ? res.permission : "private to package");
11557 }
11558 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011559 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11560 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011561 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011562 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011563 }
11564 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011565 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011566 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011567 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011568 r.lastActivity = SystemClock.uptimeMillis();
11569 synchronized (r.stats.getBatteryStats()) {
11570 r.stats.startRunningLocked();
11571 }
11572 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11573 return new ComponentName("!", "Service process is bad");
11574 }
11575 return r.name;
11576 }
11577 }
11578
11579 public ComponentName startService(IApplicationThread caller, Intent service,
11580 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011581 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 // Refuse possible leaked file descriptors
11583 if (service != null && service.hasFileDescriptors() == true) {
11584 throw new IllegalArgumentException("File descriptors passed in Intent");
11585 }
11586
Amith Yamasani742a6712011-05-04 14:49:28 -070011587 if (DEBUG_SERVICE)
11588 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589 synchronized(this) {
11590 final int callingPid = Binder.getCallingPid();
11591 final int callingUid = Binder.getCallingUid();
11592 final long origId = Binder.clearCallingIdentity();
11593 ComponentName res = startServiceLocked(caller, service,
11594 resolvedType, callingPid, callingUid);
11595 Binder.restoreCallingIdentity(origId);
11596 return res;
11597 }
11598 }
11599
11600 ComponentName startServiceInPackage(int uid,
11601 Intent service, String resolvedType) {
11602 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011603 if (DEBUG_SERVICE)
11604 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 final long origId = Binder.clearCallingIdentity();
11606 ComponentName res = startServiceLocked(null, service,
11607 resolvedType, -1, uid);
11608 Binder.restoreCallingIdentity(origId);
11609 return res;
11610 }
11611 }
11612
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011613 private void stopServiceLocked(ServiceRecord service) {
11614 synchronized (service.stats.getBatteryStats()) {
11615 service.stats.stopRunningLocked();
11616 }
11617 service.startRequested = false;
11618 service.callStart = false;
11619 bringDownServiceLocked(service, false);
11620 }
11621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 public int stopService(IApplicationThread caller, Intent service,
11623 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011624 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011625 // Refuse possible leaked file descriptors
11626 if (service != null && service.hasFileDescriptors() == true) {
11627 throw new IllegalArgumentException("File descriptors passed in Intent");
11628 }
11629
11630 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011631 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011632 + " type=" + resolvedType);
11633
11634 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11635 if (caller != null && callerApp == null) {
11636 throw new SecurityException(
11637 "Unable to find app for caller " + caller
11638 + " (pid=" + Binder.getCallingPid()
11639 + ") when stopping service " + service);
11640 }
11641
11642 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011643 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11644 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011645 if (r != null) {
11646 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011648 try {
11649 stopServiceLocked(r.record);
11650 } finally {
11651 Binder.restoreCallingIdentity(origId);
11652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 return 1;
11654 }
11655 return -1;
11656 }
11657 }
11658
11659 return 0;
11660 }
11661
11662 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011663 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011664 // Refuse possible leaked file descriptors
11665 if (service != null && service.hasFileDescriptors() == true) {
11666 throw new IllegalArgumentException("File descriptors passed in Intent");
11667 }
11668
11669 IBinder ret = null;
11670
11671 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011672 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11673 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011674
11675 if (r != null) {
11676 // r.record is null if findServiceLocked() failed the caller permission check
11677 if (r.record == null) {
11678 throw new SecurityException(
11679 "Permission Denial: Accessing service " + r.record.name
11680 + " from pid=" + Binder.getCallingPid()
11681 + ", uid=" + Binder.getCallingUid()
11682 + " requires " + r.permission);
11683 }
11684 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11685 if (ib != null) {
11686 ret = ib.binder;
11687 }
11688 }
11689 }
11690
11691 return ret;
11692 }
11693
11694 public boolean stopServiceToken(ComponentName className, IBinder token,
11695 int startId) {
11696 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011697 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011698 + " " + token + " startId=" + startId);
11699 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011700 if (r != null) {
11701 if (startId >= 0) {
11702 // Asked to only stop if done with all work. Note that
11703 // to avoid leaks, we will take this as dropping all
11704 // start items up to and including this one.
11705 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11706 if (si != null) {
11707 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011708 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11709 cur.removeUriPermissionsLocked();
11710 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011711 break;
11712 }
11713 }
11714 }
11715
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011716 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011717 return false;
11718 }
11719
11720 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011721 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011722 + " is last, but have " + r.deliveredStarts.size()
11723 + " remaining args");
11724 }
11725 }
11726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727 synchronized (r.stats.getBatteryStats()) {
11728 r.stats.stopRunningLocked();
11729 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011730 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 }
11732 final long origId = Binder.clearCallingIdentity();
11733 bringDownServiceLocked(r, false);
11734 Binder.restoreCallingIdentity(origId);
11735 return true;
11736 }
11737 }
11738 return false;
11739 }
11740
11741 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011742 int id, Notification notification, boolean removeNotification) {
11743 final long origId = Binder.clearCallingIdentity();
11744 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 synchronized(this) {
11746 ServiceRecord r = findServiceLocked(className, token);
11747 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011748 if (id != 0) {
11749 if (notification == null) {
11750 throw new IllegalArgumentException("null notification");
11751 }
11752 if (r.foregroundId != id) {
11753 r.cancelNotification();
11754 r.foregroundId = id;
11755 }
11756 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11757 r.foregroundNoti = notification;
11758 r.isForeground = true;
11759 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011760 if (r.app != null) {
11761 updateServiceForegroundLocked(r.app, true);
11762 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011763 } else {
11764 if (r.isForeground) {
11765 r.isForeground = false;
11766 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011767 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011768 updateServiceForegroundLocked(r.app, true);
11769 }
11770 }
11771 if (removeNotification) {
11772 r.cancelNotification();
11773 r.foregroundId = 0;
11774 r.foregroundNoti = null;
11775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 }
11777 }
11778 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011779 } finally {
11780 Binder.restoreCallingIdentity(origId);
11781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011782 }
11783
11784 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11785 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011786 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 if (sr.isForeground) {
11788 anyForeground = true;
11789 break;
11790 }
11791 }
11792 if (anyForeground != proc.foregroundServices) {
11793 proc.foregroundServices = anyForeground;
11794 if (oomAdj) {
11795 updateOomAdjLocked();
11796 }
11797 }
11798 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011799
11800 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11801 boolean result = false;
11802 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11803 result = false;
11804 } else if (componentProcessName == aInfo.packageName) {
11805 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11806 } else if ("system".equals(componentProcessName)) {
11807 result = true;
11808 }
11809 if (DEBUG_MU) {
11810 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11811 }
11812 return result;
11813 }
11814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 public int bindService(IApplicationThread caller, IBinder token,
11816 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011817 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011818 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011819 // Refuse possible leaked file descriptors
11820 if (service != null && service.hasFileDescriptors() == true) {
11821 throw new IllegalArgumentException("File descriptors passed in Intent");
11822 }
11823
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011824 checkValidCaller(Binder.getCallingUid(), userId);
11825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011826 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011827 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 + " type=" + resolvedType + " conn=" + connection.asBinder()
11829 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011830 if (DEBUG_MU)
11831 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11832 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011833 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11834 if (callerApp == null) {
11835 throw new SecurityException(
11836 "Unable to find app for caller " + caller
11837 + " (pid=" + Binder.getCallingPid()
11838 + ") when binding service " + service);
11839 }
11840
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011841 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011843 activity = mMainStack.isInStackLocked(token);
11844 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011845 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011846 return 0;
11847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011848 }
11849
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011850 int clientLabel = 0;
11851 PendingIntent clientIntent = null;
11852
11853 if (callerApp.info.uid == Process.SYSTEM_UID) {
11854 // Hacky kind of thing -- allow system stuff to tell us
11855 // what they are, so we can report this elsewhere for
11856 // others to know why certain services are running.
11857 try {
11858 clientIntent = (PendingIntent)service.getParcelableExtra(
11859 Intent.EXTRA_CLIENT_INTENT);
11860 } catch (RuntimeException e) {
11861 }
11862 if (clientIntent != null) {
11863 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11864 if (clientLabel != 0) {
11865 // There are no useful extras in the intent, trash them.
11866 // System code calling with this stuff just needs to know
11867 // this will happen.
11868 service = service.cloneFilter();
11869 }
11870 }
11871 }
11872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011873 ServiceLookupResult res =
11874 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011875 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011876 if (res == null) {
11877 return 0;
11878 }
11879 if (res.record == null) {
11880 return -1;
11881 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011882 if (isSingleton(res.record.processName, res.record.appInfo)) {
11883 userId = 0;
11884 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
11885 Binder.getCallingUid(), 0);
11886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011887 ServiceRecord s = res.record;
11888
11889 final long origId = Binder.clearCallingIdentity();
11890
11891 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011892 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011893 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894 }
11895
11896 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11897 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011898 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011899
11900 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011901 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11902 if (clist == null) {
11903 clist = new ArrayList<ConnectionRecord>();
11904 s.connections.put(binder, clist);
11905 }
11906 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011907 b.connections.add(c);
11908 if (activity != null) {
11909 if (activity.connections == null) {
11910 activity.connections = new HashSet<ConnectionRecord>();
11911 }
11912 activity.connections.add(c);
11913 }
11914 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011915 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11916 b.client.hasAboveClient = true;
11917 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011918 clist = mServiceConnections.get(binder);
11919 if (clist == null) {
11920 clist = new ArrayList<ConnectionRecord>();
11921 mServiceConnections.put(binder, clist);
11922 }
11923 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924
11925 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11926 s.lastActivity = SystemClock.uptimeMillis();
11927 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11928 return 0;
11929 }
11930 }
11931
11932 if (s.app != null) {
11933 // This could have made the service more important.
11934 updateOomAdjLocked(s.app);
11935 }
11936
Joe Onorato8a9b2202010-02-26 18:56:32 -080011937 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011938 + ": received=" + b.intent.received
11939 + " apps=" + b.intent.apps.size()
11940 + " doRebind=" + b.intent.doRebind);
11941
11942 if (s.app != null && b.intent.received) {
11943 // Service is already running, so we can immediately
11944 // publish the connection.
11945 try {
11946 c.conn.connected(s.name, b.intent.binder);
11947 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011948 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 + " to connection " + c.conn.asBinder()
11950 + " (in " + c.binding.client.processName + ")", e);
11951 }
11952
11953 // If this is the first app connected back to this binding,
11954 // and the service had previously asked to be told when
11955 // rebound, then do so.
11956 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11957 requestServiceBindingLocked(s, b.intent, true);
11958 }
11959 } else if (!b.intent.requested) {
11960 requestServiceBindingLocked(s, b.intent, false);
11961 }
11962
11963 Binder.restoreCallingIdentity(origId);
11964 }
11965
11966 return 1;
11967 }
11968
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011969 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011970 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011971 IBinder binder = c.conn.asBinder();
11972 AppBindRecord b = c.binding;
11973 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011974 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11975 if (clist != null) {
11976 clist.remove(c);
11977 if (clist.size() == 0) {
11978 s.connections.remove(binder);
11979 }
11980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011981 b.connections.remove(c);
11982 if (c.activity != null && c.activity != skipAct) {
11983 if (c.activity.connections != null) {
11984 c.activity.connections.remove(c);
11985 }
11986 }
11987 if (b.client != skipApp) {
11988 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011989 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11990 b.client.updateHasAboveClientLocked();
11991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011993 clist = mServiceConnections.get(binder);
11994 if (clist != null) {
11995 clist.remove(c);
11996 if (clist.size() == 0) {
11997 mServiceConnections.remove(binder);
11998 }
11999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000
12001 if (b.connections.size() == 0) {
12002 b.intent.apps.remove(b.client);
12003 }
12004
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012005 if (!c.serviceDead) {
12006 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12007 + ": shouldUnbind=" + b.intent.hasBound);
12008 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12009 && b.intent.hasBound) {
12010 try {
12011 bumpServiceExecutingLocked(s, "unbind");
12012 updateOomAdjLocked(s.app);
12013 b.intent.hasBound = false;
12014 // Assume the client doesn't want to know about a rebind;
12015 // we will deal with that later if it asks for one.
12016 b.intent.doRebind = false;
12017 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12018 } catch (Exception e) {
12019 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12020 serviceDoneExecutingLocked(s, true);
12021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012022 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012023
12024 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12025 bringDownServiceLocked(s, false);
12026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 }
12028 }
12029
12030 public boolean unbindService(IServiceConnection connection) {
12031 synchronized (this) {
12032 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012033 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012034 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12035 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012036 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012037 + connection.asBinder());
12038 return false;
12039 }
12040
12041 final long origId = Binder.clearCallingIdentity();
12042
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012043 while (clist.size() > 0) {
12044 ConnectionRecord r = clist.get(0);
12045 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012047 if (r.binding.service.app != null) {
12048 // This could have made the service less important.
12049 updateOomAdjLocked(r.binding.service.app);
12050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012051 }
12052
12053 Binder.restoreCallingIdentity(origId);
12054 }
12055
12056 return true;
12057 }
12058
12059 public void publishService(IBinder token, Intent intent, IBinder service) {
12060 // Refuse possible leaked file descriptors
12061 if (intent != null && intent.hasFileDescriptors() == true) {
12062 throw new IllegalArgumentException("File descriptors passed in Intent");
12063 }
12064
12065 synchronized(this) {
12066 if (!(token instanceof ServiceRecord)) {
12067 throw new IllegalArgumentException("Invalid service token");
12068 }
12069 ServiceRecord r = (ServiceRecord)token;
12070
12071 final long origId = Binder.clearCallingIdentity();
12072
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012073 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012074 + " " + intent + ": " + service);
12075 if (r != null) {
12076 Intent.FilterComparison filter
12077 = new Intent.FilterComparison(intent);
12078 IntentBindRecord b = r.bindings.get(filter);
12079 if (b != null && !b.received) {
12080 b.binder = service;
12081 b.requested = true;
12082 b.received = true;
12083 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012084 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012085 = r.connections.values().iterator();
12086 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012087 ArrayList<ConnectionRecord> clist = it.next();
12088 for (int i=0; i<clist.size(); i++) {
12089 ConnectionRecord c = clist.get(i);
12090 if (!filter.equals(c.binding.intent.intent)) {
12091 if (DEBUG_SERVICE) Slog.v(
12092 TAG, "Not publishing to: " + c);
12093 if (DEBUG_SERVICE) Slog.v(
12094 TAG, "Bound intent: " + c.binding.intent.intent);
12095 if (DEBUG_SERVICE) Slog.v(
12096 TAG, "Published intent: " + intent);
12097 continue;
12098 }
12099 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12100 try {
12101 c.conn.connected(r.name, service);
12102 } catch (Exception e) {
12103 Slog.w(TAG, "Failure sending service " + r.name +
12104 " to connection " + c.conn.asBinder() +
12105 " (in " + c.binding.client.processName + ")", e);
12106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 }
12108 }
12109 }
12110 }
12111
12112 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12113
12114 Binder.restoreCallingIdentity(origId);
12115 }
12116 }
12117 }
12118
12119 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12120 // Refuse possible leaked file descriptors
12121 if (intent != null && intent.hasFileDescriptors() == true) {
12122 throw new IllegalArgumentException("File descriptors passed in Intent");
12123 }
12124
12125 synchronized(this) {
12126 if (!(token instanceof ServiceRecord)) {
12127 throw new IllegalArgumentException("Invalid service token");
12128 }
12129 ServiceRecord r = (ServiceRecord)token;
12130
12131 final long origId = Binder.clearCallingIdentity();
12132
12133 if (r != null) {
12134 Intent.FilterComparison filter
12135 = new Intent.FilterComparison(intent);
12136 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012137 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 + " at " + b + ": apps="
12139 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012140
12141 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012142 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012143 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012144 // Applications have already bound since the last
12145 // unbind, so just rebind right here.
12146 requestServiceBindingLocked(r, b, true);
12147 } else {
12148 // Note to tell the service the next time there is
12149 // a new client.
12150 b.doRebind = true;
12151 }
12152 }
12153
Per Edelberg78f9fff2010-08-30 20:01:35 +020012154 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012155
12156 Binder.restoreCallingIdentity(origId);
12157 }
12158 }
12159 }
12160
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012161 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 synchronized(this) {
12163 if (!(token instanceof ServiceRecord)) {
12164 throw new IllegalArgumentException("Invalid service token");
12165 }
12166 ServiceRecord r = (ServiceRecord)token;
12167 boolean inStopping = mStoppingServices.contains(token);
12168 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012170 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012171 + " with incorrect token: given " + token
12172 + ", expected " + r);
12173 return;
12174 }
12175
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012176 if (type == 1) {
12177 // This is a call from a service start... take care of
12178 // book-keeping.
12179 r.callStart = true;
12180 switch (res) {
12181 case Service.START_STICKY_COMPATIBILITY:
12182 case Service.START_STICKY: {
12183 // We are done with the associated start arguments.
12184 r.findDeliveredStart(startId, true);
12185 // Don't stop if killed.
12186 r.stopIfKilled = false;
12187 break;
12188 }
12189 case Service.START_NOT_STICKY: {
12190 // We are done with the associated start arguments.
12191 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012192 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012193 // There is no more work, and this service
12194 // doesn't want to hang around if killed.
12195 r.stopIfKilled = true;
12196 }
12197 break;
12198 }
12199 case Service.START_REDELIVER_INTENT: {
12200 // We'll keep this item until they explicitly
12201 // call stop for it, but keep track of the fact
12202 // that it was delivered.
12203 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12204 if (si != null) {
12205 si.deliveryCount = 0;
12206 si.doneExecutingCount++;
12207 // Don't stop if killed.
12208 r.stopIfKilled = true;
12209 }
12210 break;
12211 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012212 case Service.START_TASK_REMOVED_COMPLETE: {
12213 // Special processing for onTaskRemoved(). Don't
12214 // impact normal onStartCommand() processing.
12215 r.findDeliveredStart(startId, true);
12216 break;
12217 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012218 default:
12219 throw new IllegalArgumentException(
12220 "Unknown service start result: " + res);
12221 }
12222 if (res == Service.START_STICKY_COMPATIBILITY) {
12223 r.callStart = false;
12224 }
12225 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012226 if (DEBUG_MU)
12227 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12228 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 final long origId = Binder.clearCallingIdentity();
12230 serviceDoneExecutingLocked(r, inStopping);
12231 Binder.restoreCallingIdentity(origId);
12232 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012233 Slog.w(TAG, "Done executing unknown service from pid "
12234 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 }
12236 }
12237 }
12238
12239 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012240 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12241 + ": nesting=" + r.executeNesting
12242 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012243 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 r.executeNesting--;
12245 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012246 if (DEBUG_SERVICE) Slog.v(TAG,
12247 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248 r.app.executingServices.remove(r);
12249 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012250 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12251 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012252 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12253 }
12254 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012255 if (DEBUG_SERVICE) Slog.v(TAG,
12256 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012257 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012258 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012259 }
12260 updateOomAdjLocked(r.app);
12261 }
12262 }
12263
12264 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012265 String anrMessage = null;
12266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012267 synchronized(this) {
12268 if (proc.executingServices.size() == 0 || proc.thread == null) {
12269 return;
12270 }
12271 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12272 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12273 ServiceRecord timeout = null;
12274 long nextTime = 0;
12275 while (it.hasNext()) {
12276 ServiceRecord sr = it.next();
12277 if (sr.executingStart < maxTime) {
12278 timeout = sr;
12279 break;
12280 }
12281 if (sr.executingStart > nextTime) {
12282 nextTime = sr.executingStart;
12283 }
12284 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012285 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012286 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012287 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012288 } else {
12289 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12290 msg.obj = proc;
12291 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12292 }
12293 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012294
12295 if (anrMessage != null) {
12296 appNotResponding(proc, null, null, anrMessage);
12297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012298 }
12299
12300 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012301 // BACKUP AND RESTORE
12302 // =========================================================
12303
12304 // Cause the target app to be launched if necessary and its backup agent
12305 // instantiated. The backup agent will invoke backupAgentCreated() on the
12306 // activity manager to announce its creation.
12307 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012308 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012309 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12310
12311 synchronized(this) {
12312 // !!! TODO: currently no check here that we're already bound
12313 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12314 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12315 synchronized (stats) {
12316 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12317 }
12318
Dianne Hackborne7f97212011-02-24 14:40:20 -080012319 // Backup agent is now in use, its package can't be stopped.
12320 try {
12321 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012322 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012323 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012324 } catch (IllegalArgumentException e) {
12325 Slog.w(TAG, "Failed trying to unstop package "
12326 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012327 }
12328
Christopher Tate181fafa2009-05-14 11:12:14 -070012329 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012330 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12331 ? new ComponentName(app.packageName, app.backupAgentName)
12332 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012333 // startProcessLocked() returns existing proc's record if it's already running
12334 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012335 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012336 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012337 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012338 return false;
12339 }
12340
12341 r.app = proc;
12342 mBackupTarget = r;
12343 mBackupAppName = app.packageName;
12344
Christopher Tate6fa95972009-06-05 18:43:55 -070012345 // Try not to kill the process during backup
12346 updateOomAdjLocked(proc);
12347
Christopher Tate181fafa2009-05-14 11:12:14 -070012348 // If the process is already attached, schedule the creation of the backup agent now.
12349 // If it is not yet live, this will be done when it attaches to the framework.
12350 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012351 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012352 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012353 proc.thread.scheduleCreateBackupAgent(app,
12354 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012355 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012356 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012357 }
12358 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012359 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012360 }
12361 // Invariants: at this point, the target app process exists and the application
12362 // is either already running or in the process of coming up. mBackupTarget and
12363 // mBackupAppName describe the app, so that when it binds back to the AM we
12364 // know that it's scheduled for a backup-agent operation.
12365 }
12366
12367 return true;
12368 }
12369
12370 // A backup agent has just come up
12371 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012372 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012373 + " = " + agent);
12374
12375 synchronized(this) {
12376 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012377 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012378 return;
12379 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012380 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012381
Dianne Hackborn06740692010-09-22 22:46:21 -070012382 long oldIdent = Binder.clearCallingIdentity();
12383 try {
12384 IBackupManager bm = IBackupManager.Stub.asInterface(
12385 ServiceManager.getService(Context.BACKUP_SERVICE));
12386 bm.agentConnected(agentPackageName, agent);
12387 } catch (RemoteException e) {
12388 // can't happen; the backup manager service is local
12389 } catch (Exception e) {
12390 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12391 e.printStackTrace();
12392 } finally {
12393 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012394 }
12395 }
12396
12397 // done with this agent
12398 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012399 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012400 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012401 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012402 return;
12403 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012404
12405 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012406 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012407 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012408 return;
12409 }
12410
Christopher Tate181fafa2009-05-14 11:12:14 -070012411 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012412 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012413 return;
12414 }
12415
Christopher Tate6fa95972009-06-05 18:43:55 -070012416 ProcessRecord proc = mBackupTarget.app;
12417 mBackupTarget = null;
12418 mBackupAppName = null;
12419
12420 // Not backing this app up any more; reset its OOM adjustment
12421 updateOomAdjLocked(proc);
12422
Christopher Tatec7b31e32009-06-10 15:49:30 -070012423 // If the app crashed during backup, 'thread' will be null here
12424 if (proc.thread != null) {
12425 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012426 proc.thread.scheduleDestroyBackupAgent(appInfo,
12427 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012428 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012429 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012430 e.printStackTrace();
12431 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012432 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012433 }
12434 }
12435 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012436 // BROADCASTS
12437 // =========================================================
12438
Josh Bartel7f208742010-02-25 11:01:44 -060012439 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440 List cur) {
12441 final ContentResolver resolver = mContext.getContentResolver();
12442 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12443 if (list == null) {
12444 return cur;
12445 }
12446 int N = list.size();
12447 for (int i=0; i<N; i++) {
12448 Intent intent = list.get(i);
12449 if (filter.match(resolver, intent, true, TAG) >= 0) {
12450 if (cur == null) {
12451 cur = new ArrayList<Intent>();
12452 }
12453 cur.add(intent);
12454 }
12455 }
12456 return cur;
12457 }
12458
Christopher Tatef46723b2012-01-26 14:19:24 -080012459 boolean isPendingBroadcastProcessLocked(int pid) {
12460 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12461 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012463
Christopher Tatef46723b2012-01-26 14:19:24 -080012464 void skipPendingBroadcastLocked(int pid) {
12465 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12466 for (BroadcastQueue queue : mBroadcastQueues) {
12467 queue.skipPendingBroadcastLocked(pid);
12468 }
12469 }
12470
12471 // The app just attached; send any pending broadcasts that it should receive
12472 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12473 boolean didSomething = false;
12474 for (BroadcastQueue queue : mBroadcastQueues) {
12475 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012476 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012477 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 }
12479
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012480 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012481 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012482 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012483 synchronized(this) {
12484 ProcessRecord callerApp = null;
12485 if (caller != null) {
12486 callerApp = getRecordForAppLocked(caller);
12487 if (callerApp == null) {
12488 throw new SecurityException(
12489 "Unable to find app for caller " + caller
12490 + " (pid=" + Binder.getCallingPid()
12491 + ") when registering receiver " + receiver);
12492 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012493 if (callerApp.info.uid != Process.SYSTEM_UID &&
12494 !callerApp.pkgList.contains(callerPackage)) {
12495 throw new SecurityException("Given caller package " + callerPackage
12496 + " is not running in process " + callerApp);
12497 }
12498 } else {
12499 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 }
12501
12502 List allSticky = null;
12503
12504 // Look for any matching sticky broadcasts...
12505 Iterator actions = filter.actionsIterator();
12506 if (actions != null) {
12507 while (actions.hasNext()) {
12508 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012509 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012510 }
12511 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012512 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012513 }
12514
12515 // The first sticky in the list is returned directly back to
12516 // the client.
12517 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12518
Joe Onorato8a9b2202010-02-26 18:56:32 -080012519 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012520 + ": " + sticky);
12521
12522 if (receiver == null) {
12523 return sticky;
12524 }
12525
12526 ReceiverList rl
12527 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12528 if (rl == null) {
12529 rl = new ReceiverList(this, callerApp,
12530 Binder.getCallingPid(),
12531 Binder.getCallingUid(), receiver);
12532 if (rl.app != null) {
12533 rl.app.receivers.add(rl);
12534 } else {
12535 try {
12536 receiver.asBinder().linkToDeath(rl, 0);
12537 } catch (RemoteException e) {
12538 return sticky;
12539 }
12540 rl.linkedToDeath = true;
12541 }
12542 mRegisteredReceivers.put(receiver.asBinder(), rl);
12543 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012544 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012545 rl.add(bf);
12546 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012547 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012548 }
12549 mReceiverResolver.addFilter(bf);
12550
12551 // Enqueue broadcasts for all existing stickies that match
12552 // this filter.
12553 if (allSticky != null) {
12554 ArrayList receivers = new ArrayList();
12555 receivers.add(bf);
12556
12557 int N = allSticky.size();
12558 for (int i=0; i<N; i++) {
12559 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012560 BroadcastQueue queue = broadcastQueueForIntent(intent);
12561 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012563 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012564 queue.enqueueParallelBroadcastLocked(r);
12565 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012566 }
12567 }
12568
12569 return sticky;
12570 }
12571 }
12572
12573 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012574 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012575
Christopher Tatef46723b2012-01-26 14:19:24 -080012576 final long origId = Binder.clearCallingIdentity();
12577 try {
12578 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012579
Christopher Tatef46723b2012-01-26 14:19:24 -080012580 synchronized(this) {
12581 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012582 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012583 if (rl != null) {
12584 if (rl.curBroadcast != null) {
12585 BroadcastRecord r = rl.curBroadcast;
12586 final boolean doNext = finishReceiverLocked(
12587 receiver.asBinder(), r.resultCode, r.resultData,
12588 r.resultExtras, r.resultAbort, true);
12589 if (doNext) {
12590 doTrim = true;
12591 r.queue.processNextBroadcast(false);
12592 }
12593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594
Christopher Tatef46723b2012-01-26 14:19:24 -080012595 if (rl.app != null) {
12596 rl.app.receivers.remove(rl);
12597 }
12598 removeReceiverLocked(rl);
12599 if (rl.linkedToDeath) {
12600 rl.linkedToDeath = false;
12601 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012603 }
12604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012605
Christopher Tatef46723b2012-01-26 14:19:24 -080012606 // If we actually concluded any broadcasts, we might now be able
12607 // to trim the recipients' apps from our working set
12608 if (doTrim) {
12609 trimApplications();
12610 return;
12611 }
12612
12613 } finally {
12614 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012616 }
12617
12618 void removeReceiverLocked(ReceiverList rl) {
12619 mRegisteredReceivers.remove(rl.receiver.asBinder());
12620 int N = rl.size();
12621 for (int i=0; i<N; i++) {
12622 mReceiverResolver.removeFilter(rl.get(i));
12623 }
12624 }
12625
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012626 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12627 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12628 ProcessRecord r = mLruProcesses.get(i);
12629 if (r.thread != null) {
12630 try {
12631 r.thread.dispatchPackageBroadcast(cmd, packages);
12632 } catch (RemoteException ex) {
12633 }
12634 }
12635 }
12636 }
12637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 private final int broadcastIntentLocked(ProcessRecord callerApp,
12639 String callerPackage, Intent intent, String resolvedType,
12640 IIntentReceiver resultTo, int resultCode, String resultData,
12641 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012642 boolean ordered, boolean sticky, int callingPid, int callingUid,
12643 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012644 intent = new Intent(intent);
12645
Dianne Hackborne7f97212011-02-24 14:40:20 -080012646 // By default broadcasts do not go to stopped apps.
12647 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12648
Joe Onorato8a9b2202010-02-26 18:56:32 -080012649 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012650 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012651 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012652 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012653 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012654 }
12655
12656 // Handle special intents: if this broadcast is from the package
12657 // manager about a package being removed, we need to remove all of
12658 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012659 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012660 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012661 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12662 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012663 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664 || uidRemoved) {
12665 if (checkComponentPermission(
12666 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012667 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012668 == PackageManager.PERMISSION_GRANTED) {
12669 if (uidRemoved) {
12670 final Bundle intentExtras = intent.getExtras();
12671 final int uid = intentExtras != null
12672 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12673 if (uid >= 0) {
12674 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12675 synchronized (bs) {
12676 bs.removeUidStatsLocked(uid);
12677 }
12678 }
12679 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012680 // If resources are unvailble just force stop all
12681 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012682 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012683 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12684 if (list != null && (list.length > 0)) {
12685 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012686 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012687 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012688 sendPackageBroadcastLocked(
12689 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012690 }
12691 } else {
12692 Uri data = intent.getData();
12693 String ssp;
12694 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12695 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12696 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012697 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12698 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012699 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012700 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012701 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12702 new String[] {ssp});
12703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012704 }
12705 }
12706 }
12707 } else {
12708 String msg = "Permission Denial: " + intent.getAction()
12709 + " broadcast from " + callerPackage + " (pid=" + callingPid
12710 + ", uid=" + callingUid + ")"
12711 + " requires "
12712 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012713 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012714 throw new SecurityException(msg);
12715 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012716
12717 // Special case for adding a package: by default turn on compatibility
12718 // mode.
12719 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012720 Uri data = intent.getData();
12721 String ssp;
12722 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12723 mCompatModePackages.handlePackageAddedLocked(ssp,
12724 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012726 }
12727
12728 /*
12729 * If this is the time zone changed action, queue up a message that will reset the timezone
12730 * of all currently running processes. This message will get queued up before the broadcast
12731 * happens.
12732 */
12733 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12734 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12735 }
12736
Robert Greenwalt03595d02010-11-02 14:08:23 -070012737 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12738 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12739 }
12740
Robert Greenwalt434203a2010-10-11 16:00:27 -070012741 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12742 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12743 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12744 }
12745
Dianne Hackborn854060af2009-07-09 18:14:31 -070012746 /*
12747 * Prevent non-system code (defined here to be non-persistent
12748 * processes) from sending protected broadcasts.
12749 */
12750 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12751 || callingUid == Process.SHELL_UID || callingUid == 0) {
12752 // Always okay.
12753 } else if (callerApp == null || !callerApp.persistent) {
12754 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012755 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012756 intent.getAction())) {
12757 String msg = "Permission Denial: not allowed to send broadcast "
12758 + intent.getAction() + " from pid="
12759 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012760 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012761 throw new SecurityException(msg);
12762 }
12763 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012764 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012765 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012766 }
12767 }
12768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012769 // Add to the sticky list if requested.
12770 if (sticky) {
12771 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12772 callingPid, callingUid)
12773 != PackageManager.PERMISSION_GRANTED) {
12774 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12775 + callingPid + ", uid=" + callingUid
12776 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012777 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012778 throw new SecurityException(msg);
12779 }
12780 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012781 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012782 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012783 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 }
12785 if (intent.getComponent() != null) {
12786 throw new SecurityException(
12787 "Sticky broadcasts can't target a specific component");
12788 }
12789 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12790 if (list == null) {
12791 list = new ArrayList<Intent>();
12792 mStickyBroadcasts.put(intent.getAction(), list);
12793 }
12794 int N = list.size();
12795 int i;
12796 for (i=0; i<N; i++) {
12797 if (intent.filterEquals(list.get(i))) {
12798 // This sticky already exists, replace it.
12799 list.set(i, new Intent(intent));
12800 break;
12801 }
12802 }
12803 if (i >= N) {
12804 list.add(new Intent(intent));
12805 }
12806 }
12807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 // Figure out who all will receive this broadcast.
12809 List receivers = null;
12810 List<BroadcastFilter> registeredReceivers = null;
12811 try {
12812 if (intent.getComponent() != null) {
12813 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012814 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012815 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012816 if (ai != null) {
12817 receivers = new ArrayList();
12818 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012819 if (isSingleton(ai.processName, ai.applicationInfo)) {
12820 ri.activityInfo = getActivityInfoForUser(ai, 0);
12821 } else {
12822 ri.activityInfo = getActivityInfoForUser(ai, userId);
12823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 receivers.add(ri);
12825 }
12826 } else {
12827 // Need to resolve the intent to interested receivers...
12828 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12829 == 0) {
12830 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012831 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012832 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012834 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12835 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012836 }
12837 } catch (RemoteException ex) {
12838 // pm is in same process, this will never happen.
12839 }
12840
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012841 final boolean replacePending =
12842 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12843
Joe Onorato8a9b2202010-02-26 18:56:32 -080012844 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012845 + " replacePending=" + replacePending);
12846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012847 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12848 if (!ordered && NR > 0) {
12849 // If we are not serializing this broadcast, then send the
12850 // registered receivers separately so they don't wait for the
12851 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012852 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12853 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012854 callerPackage, callingPid, callingUid, requiredPermission,
12855 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012856 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012857 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012858 TAG, "Enqueueing parallel broadcast " + r);
12859 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012860 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012861 queue.enqueueParallelBroadcastLocked(r);
12862 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 registeredReceivers = null;
12865 NR = 0;
12866 }
12867
12868 // Merge into one list.
12869 int ir = 0;
12870 if (receivers != null) {
12871 // A special case for PACKAGE_ADDED: do not allow the package
12872 // being added to see this broadcast. This prevents them from
12873 // using this as a back door to get run as soon as they are
12874 // installed. Maybe in the future we want to have a special install
12875 // broadcast or such for apps, but we'd like to deliberately make
12876 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012877 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012878 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12879 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12880 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012881 Uri data = intent.getData();
12882 if (data != null) {
12883 String pkgName = data.getSchemeSpecificPart();
12884 if (pkgName != null) {
12885 skipPackages = new String[] { pkgName };
12886 }
12887 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012888 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012889 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012890 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012891 if (skipPackages != null && (skipPackages.length > 0)) {
12892 for (String skipPackage : skipPackages) {
12893 if (skipPackage != null) {
12894 int NT = receivers.size();
12895 for (int it=0; it<NT; it++) {
12896 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12897 if (curt.activityInfo.packageName.equals(skipPackage)) {
12898 receivers.remove(it);
12899 it--;
12900 NT--;
12901 }
12902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903 }
12904 }
12905 }
12906
12907 int NT = receivers != null ? receivers.size() : 0;
12908 int it = 0;
12909 ResolveInfo curt = null;
12910 BroadcastFilter curr = null;
12911 while (it < NT && ir < NR) {
12912 if (curt == null) {
12913 curt = (ResolveInfo)receivers.get(it);
12914 }
12915 if (curr == null) {
12916 curr = registeredReceivers.get(ir);
12917 }
12918 if (curr.getPriority() >= curt.priority) {
12919 // Insert this broadcast record into the final list.
12920 receivers.add(it, curr);
12921 ir++;
12922 curr = null;
12923 it++;
12924 NT++;
12925 } else {
12926 // Skip to the next ResolveInfo in the final list.
12927 it++;
12928 curt = null;
12929 }
12930 }
12931 }
12932 while (ir < NR) {
12933 if (receivers == null) {
12934 receivers = new ArrayList();
12935 }
12936 receivers.add(registeredReceivers.get(ir));
12937 ir++;
12938 }
12939
12940 if ((receivers != null && receivers.size() > 0)
12941 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012942 BroadcastQueue queue = broadcastQueueForIntent(intent);
12943 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012945 receivers, resultTo, resultCode, resultData, map, ordered,
12946 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012947 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012948 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012949 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012950 if (DEBUG_BROADCAST) {
12951 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012952 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012954 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012955 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012956 queue.enqueueOrderedBroadcastLocked(r);
12957 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 }
12960
Dianne Hackborna4972e92012-03-14 10:38:05 -070012961 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 }
12963
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012964 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012965 // Refuse possible leaked file descriptors
12966 if (intent != null && intent.hasFileDescriptors() == true) {
12967 throw new IllegalArgumentException("File descriptors passed in Intent");
12968 }
12969
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012970 int flags = intent.getFlags();
12971
12972 if (!mProcessesReady) {
12973 // if the caller really truly claims to know what they're doing, go
12974 // ahead and allow the broadcast without launching any receivers
12975 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12976 intent = new Intent(intent);
12977 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12978 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12979 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12980 + " before boot completion");
12981 throw new IllegalStateException("Cannot broadcast before boot completed");
12982 }
12983 }
12984
12985 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12986 throw new IllegalArgumentException(
12987 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12988 }
12989
12990 return intent;
12991 }
12992
12993 public final int broadcastIntent(IApplicationThread caller,
12994 Intent intent, String resolvedType, IIntentReceiver resultTo,
12995 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012996 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012997 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012999 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013001 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13002 final int callingPid = Binder.getCallingPid();
13003 final int callingUid = Binder.getCallingUid();
13004 final long origId = Binder.clearCallingIdentity();
13005 int res = broadcastIntentLocked(callerApp,
13006 callerApp != null ? callerApp.info.packageName : null,
13007 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013008 resultCode, resultData, map, requiredPermission, serialized, sticky,
13009 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010 Binder.restoreCallingIdentity(origId);
13011 return res;
13012 }
13013 }
13014
13015 int broadcastIntentInPackage(String packageName, int uid,
13016 Intent intent, String resolvedType, IIntentReceiver resultTo,
13017 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013018 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013020 intent = verifyBroadcastLocked(intent);
13021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013022 final long origId = Binder.clearCallingIdentity();
13023 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13024 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013025 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 Binder.restoreCallingIdentity(origId);
13027 return res;
13028 }
13029 }
13030
Amith Yamasani742a6712011-05-04 14:49:28 -070013031 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13032 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013033 // Refuse possible leaked file descriptors
13034 if (intent != null && intent.hasFileDescriptors() == true) {
13035 throw new IllegalArgumentException("File descriptors passed in Intent");
13036 }
13037
13038 synchronized(this) {
13039 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13040 != PackageManager.PERMISSION_GRANTED) {
13041 String msg = "Permission Denial: unbroadcastIntent() from pid="
13042 + Binder.getCallingPid()
13043 + ", uid=" + Binder.getCallingUid()
13044 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013045 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 throw new SecurityException(msg);
13047 }
13048 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13049 if (list != null) {
13050 int N = list.size();
13051 int i;
13052 for (i=0; i<N; i++) {
13053 if (intent.filterEquals(list.get(i))) {
13054 list.remove(i);
13055 break;
13056 }
13057 }
13058 }
13059 }
13060 }
13061
13062 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13063 String resultData, Bundle resultExtras, boolean resultAbort,
13064 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013065 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13066 if (r == null) {
13067 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013068 return false;
13069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013070
Christopher Tatef46723b2012-01-26 14:19:24 -080013071 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13072 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013073 }
13074
13075 public void finishReceiver(IBinder who, int resultCode, String resultData,
13076 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013077 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078
13079 // Refuse possible leaked file descriptors
13080 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13081 throw new IllegalArgumentException("File descriptors passed in Bundle");
13082 }
13083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013084 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013085 try {
13086 boolean doNext = false;
13087 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088
Christopher Tatef46723b2012-01-26 14:19:24 -080013089 synchronized(this) {
13090 r = broadcastRecordForReceiverLocked(who);
13091 if (r != null) {
13092 doNext = r.queue.finishReceiverLocked(r, resultCode,
13093 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013095 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013096
Christopher Tatef46723b2012-01-26 14:19:24 -080013097 if (doNext) {
13098 r.queue.processNextBroadcast(false);
13099 }
13100 trimApplications();
13101 } finally {
13102 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 // =========================================================
13107 // INSTRUMENTATION
13108 // =========================================================
13109
13110 public boolean startInstrumentation(ComponentName className,
13111 String profileFile, int flags, Bundle arguments,
13112 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013113 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 // Refuse possible leaked file descriptors
13115 if (arguments != null && arguments.hasFileDescriptors()) {
13116 throw new IllegalArgumentException("File descriptors passed in Bundle");
13117 }
13118
13119 synchronized(this) {
13120 InstrumentationInfo ii = null;
13121 ApplicationInfo ai = null;
13122 try {
13123 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013124 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013125 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013126 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013127 } catch (PackageManager.NameNotFoundException e) {
13128 }
13129 if (ii == null) {
13130 reportStartInstrumentationFailure(watcher, className,
13131 "Unable to find instrumentation info for: " + className);
13132 return false;
13133 }
13134 if (ai == null) {
13135 reportStartInstrumentationFailure(watcher, className,
13136 "Unable to find instrumentation target package: " + ii.targetPackage);
13137 return false;
13138 }
13139
13140 int match = mContext.getPackageManager().checkSignatures(
13141 ii.targetPackage, ii.packageName);
13142 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13143 String msg = "Permission Denial: starting instrumentation "
13144 + className + " from pid="
13145 + Binder.getCallingPid()
13146 + ", uid=" + Binder.getCallingPid()
13147 + " not allowed because package " + ii.packageName
13148 + " does not have a signature matching the target "
13149 + ii.targetPackage;
13150 reportStartInstrumentationFailure(watcher, className, msg);
13151 throw new SecurityException(msg);
13152 }
13153
Amith Yamasani483f3b02012-03-13 16:08:00 -070013154 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013155 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013156 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013157 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013158 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013159 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013160 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013161 app.instrumentationProfileFile = profileFile;
13162 app.instrumentationArguments = arguments;
13163 app.instrumentationWatcher = watcher;
13164 app.instrumentationResultClass = className;
13165 Binder.restoreCallingIdentity(origId);
13166 }
13167
13168 return true;
13169 }
13170
13171 /**
13172 * Report errors that occur while attempting to start Instrumentation. Always writes the
13173 * error to the logs, but if somebody is watching, send the report there too. This enables
13174 * the "am" command to report errors with more information.
13175 *
13176 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13177 * @param cn The component name of the instrumentation.
13178 * @param report The error report.
13179 */
13180 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13181 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013182 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013183 try {
13184 if (watcher != null) {
13185 Bundle results = new Bundle();
13186 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13187 results.putString("Error", report);
13188 watcher.instrumentationStatus(cn, -1, results);
13189 }
13190 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013191 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013192 }
13193 }
13194
13195 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13196 if (app.instrumentationWatcher != null) {
13197 try {
13198 // NOTE: IInstrumentationWatcher *must* be oneway here
13199 app.instrumentationWatcher.instrumentationFinished(
13200 app.instrumentationClass,
13201 resultCode,
13202 results);
13203 } catch (RemoteException e) {
13204 }
13205 }
13206 app.instrumentationWatcher = null;
13207 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013208 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013209 app.instrumentationProfileFile = null;
13210 app.instrumentationArguments = null;
13211
Amith Yamasani483f3b02012-03-13 16:08:00 -070013212 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 }
13214
13215 public void finishInstrumentation(IApplicationThread target,
13216 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013217 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013218 // Refuse possible leaked file descriptors
13219 if (results != null && results.hasFileDescriptors()) {
13220 throw new IllegalArgumentException("File descriptors passed in Intent");
13221 }
13222
13223 synchronized(this) {
13224 ProcessRecord app = getRecordForAppLocked(target);
13225 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013226 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013227 return;
13228 }
13229 final long origId = Binder.clearCallingIdentity();
13230 finishInstrumentationLocked(app, resultCode, results);
13231 Binder.restoreCallingIdentity(origId);
13232 }
13233 }
13234
13235 // =========================================================
13236 // CONFIGURATION
13237 // =========================================================
13238
13239 public ConfigurationInfo getDeviceConfigurationInfo() {
13240 ConfigurationInfo config = new ConfigurationInfo();
13241 synchronized (this) {
13242 config.reqTouchScreen = mConfiguration.touchscreen;
13243 config.reqKeyboardType = mConfiguration.keyboard;
13244 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013245 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13246 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013247 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13248 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013249 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13250 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13252 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013253 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013254 }
13255 return config;
13256 }
13257
13258 public Configuration getConfiguration() {
13259 Configuration ci;
13260 synchronized(this) {
13261 ci = new Configuration(mConfiguration);
13262 }
13263 return ci;
13264 }
13265
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013266 public void updatePersistentConfiguration(Configuration values) {
13267 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13268 "updateConfiguration()");
13269 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13270 "updateConfiguration()");
13271 if (values == null) {
13272 throw new NullPointerException("Configuration must not be null");
13273 }
13274
13275 synchronized(this) {
13276 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013277 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013278 Binder.restoreCallingIdentity(origId);
13279 }
13280 }
13281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013282 public void updateConfiguration(Configuration values) {
13283 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13284 "updateConfiguration()");
13285
13286 synchronized(this) {
13287 if (values == null && mWindowManager != null) {
13288 // sentinel: fetch the current configuration from the window manager
13289 values = mWindowManager.computeNewConfiguration();
13290 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013291
13292 if (mWindowManager != null) {
13293 mProcessList.applyDisplaySize(mWindowManager);
13294 }
13295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013296 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013297 if (values != null) {
13298 Settings.System.clearConfiguration(values);
13299 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013300 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 Binder.restoreCallingIdentity(origId);
13302 }
13303 }
13304
13305 /**
13306 * Do either or both things: (1) change the current configuration, and (2)
13307 * make sure the given activity is running with the (now) current
13308 * configuration. Returns true if the activity has been left running, or
13309 * false if <var>starting</var> is being destroyed to match the new
13310 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013311 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013313 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013314 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013315 // do nothing if we are headless
13316 if (mHeadless) return true;
13317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318 int changes = 0;
13319
13320 boolean kept = true;
13321
13322 if (values != null) {
13323 Configuration newConfig = new Configuration(mConfiguration);
13324 changes = newConfig.updateFrom(values);
13325 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013326 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013327 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013328 }
13329
Doug Zongker2bec3d42009-12-04 12:52:44 -080013330 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331
Dianne Hackborn813075a62011-11-14 17:45:19 -080013332 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333 saveLocaleLocked(values.locale,
13334 !values.locale.equals(mConfiguration.locale),
13335 values.userSetLocale);
13336 }
13337
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013338 mConfigurationSeq++;
13339 if (mConfigurationSeq <= 0) {
13340 mConfigurationSeq = 1;
13341 }
13342 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013343 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013344 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013345
13346 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013347
13348 // TODO: If our config changes, should we auto dismiss any currently
13349 // showing dialogs?
13350 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013351
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013352 AttributeCache ac = AttributeCache.instance();
13353 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013354 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013356
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013357 // Make sure all resources in our process are updated
13358 // right now, so that anyone who is going to retrieve
13359 // resource values after we return will be sure to get
13360 // the new ones. This is especially important during
13361 // boot, where the first config change needs to guarantee
13362 // all resources have that config before following boot
13363 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013364 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013365
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013366 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013367 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013368 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013369 mHandler.sendMessage(msg);
13370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013371
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013372 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13373 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 try {
13375 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013376 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013377 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013378 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013379 }
13380 } catch (Exception e) {
13381 }
13382 }
13383 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013384 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13385 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013386 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013387 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013388 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13389 broadcastIntentLocked(null, null,
13390 new Intent(Intent.ACTION_LOCALE_CHANGED),
13391 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013392 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013394 }
13395 }
13396
13397 if (changes != 0 && starting == null) {
13398 // If the configuration changed, and the caller is not already
13399 // in the process of starting an activity, then find the top
13400 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013401 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013402 }
13403
13404 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013405 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013406 // And we need to make sure at this point that all other activities
13407 // are made visible with the correct configuration.
13408 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013409 }
13410
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013411 if (values != null && mWindowManager != null) {
13412 mWindowManager.setNewConfiguration(mConfiguration);
13413 }
13414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013415 return kept;
13416 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013417
13418 /**
13419 * Decide based on the configuration whether we should shouw the ANR,
13420 * crash, etc dialogs. The idea is that if there is no affordnace to
13421 * press the on-screen buttons, we shouldn't show the dialog.
13422 *
13423 * A thought: SystemUI might also want to get told about this, the Power
13424 * dialog / global actions also might want different behaviors.
13425 */
13426 private static final boolean shouldShowDialogs(Configuration config) {
13427 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13428 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013430
13431 /**
13432 * Save the locale. You must be inside a synchronized (this) block.
13433 */
13434 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13435 if(isDiff) {
13436 SystemProperties.set("user.language", l.getLanguage());
13437 SystemProperties.set("user.region", l.getCountry());
13438 }
13439
13440 if(isPersist) {
13441 SystemProperties.set("persist.sys.language", l.getLanguage());
13442 SystemProperties.set("persist.sys.country", l.getCountry());
13443 SystemProperties.set("persist.sys.localevar", l.getVariant());
13444 }
13445 }
13446
Adam Powelldd8fab22012-03-22 17:47:27 -070013447 @Override
13448 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13449 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013450 return srec != null && srec.task.affinity != null &&
13451 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013452 }
13453
13454 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13455 Intent resultData) {
13456 ComponentName dest = destIntent.getComponent();
13457
13458 synchronized (this) {
13459 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013460 if (srec == null) {
13461 return false;
13462 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013463 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13464 final int start = history.indexOf(srec);
13465 if (start < 0) {
13466 // Current activity is not in history stack; do nothing.
13467 return false;
13468 }
13469 int finishTo = start - 1;
13470 ActivityRecord parent = null;
13471 boolean foundParentInTask = false;
13472 if (dest != null) {
13473 TaskRecord tr = srec.task;
13474 for (int i = start - 1; i >= 0; i--) {
13475 ActivityRecord r = history.get(i);
13476 if (tr != r.task) {
13477 // Couldn't find parent in the same task; stop at the one above this.
13478 // (Root of current task; in-app "home" behavior)
13479 // Always at least finish the current activity.
13480 finishTo = Math.min(start - 1, i + 1);
13481 parent = history.get(finishTo);
13482 break;
13483 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13484 r.info.name.equals(dest.getClassName())) {
13485 finishTo = i;
13486 parent = r;
13487 foundParentInTask = true;
13488 break;
13489 }
13490 }
13491 }
13492
13493 if (mController != null) {
13494 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13495 if (next != null) {
13496 // ask watcher if this is allowed
13497 boolean resumeOK = true;
13498 try {
13499 resumeOK = mController.activityResuming(next.packageName);
13500 } catch (RemoteException e) {
13501 mController = null;
13502 }
13503
13504 if (!resumeOK) {
13505 return false;
13506 }
13507 }
13508 }
13509 final long origId = Binder.clearCallingIdentity();
13510 for (int i = start; i > finishTo; i--) {
13511 ActivityRecord r = history.get(i);
13512 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13513 "navigate-up");
13514 // Only return the supplied result for the first activity finished
13515 resultCode = Activity.RESULT_CANCELED;
13516 resultData = null;
13517 }
13518
13519 if (parent != null && foundParentInTask) {
13520 final int parentLaunchMode = parent.info.launchMode;
13521 final int destIntentFlags = destIntent.getFlags();
13522 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13523 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13524 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13525 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070013526 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070013527 } else {
13528 try {
13529 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13530 destIntent.getComponent(), 0, UserId.getCallingUserId());
13531 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13532 null, aInfo, parent.appToken, null,
13533 0, -1, parent.launchedFromUid, 0, null, true, null);
13534 foundParentInTask = res == ActivityManager.START_SUCCESS;
13535 } catch (RemoteException e) {
13536 foundParentInTask = false;
13537 }
13538 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13539 resultData, "navigate-up");
13540 }
13541 }
13542 Binder.restoreCallingIdentity(origId);
13543 return foundParentInTask;
13544 }
13545 }
13546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547 // =========================================================
13548 // LIFETIME MANAGEMENT
13549 // =========================================================
13550
Christopher Tatef46723b2012-01-26 14:19:24 -080013551 // Returns which broadcast queue the app is the current [or imminent] receiver
13552 // on, or 'null' if the app is not an active broadcast recipient.
13553 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13554 BroadcastRecord r = app.curReceiver;
13555 if (r != null) {
13556 return r.queue;
13557 }
13558
13559 // It's not the current receiver, but it might be starting up to become one
13560 synchronized (this) {
13561 for (BroadcastQueue queue : mBroadcastQueues) {
13562 r = queue.mPendingBroadcast;
13563 if (r != null && r.curApp == app) {
13564 // found it; report which queue it's in
13565 return queue;
13566 }
13567 }
13568 }
13569
13570 return null;
13571 }
13572
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013573 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013574 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013575 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013576 // This adjustment has already been computed. If we are calling
13577 // from the top, we may have already computed our adjustment with
13578 // an earlier hidden adjustment that isn't really for us... if
13579 // so, use the new hidden adjustment.
13580 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013581 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013582 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013583 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 }
13585
13586 if (app.thread == null) {
13587 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013588 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013589 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590 }
13591
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013592 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13593 app.adjSource = null;
13594 app.adjTarget = null;
13595 app.empty = false;
13596 app.hidden = false;
13597
13598 final int activitiesSize = app.activities.size();
13599
Dianne Hackborn7d608422011-08-07 16:24:18 -070013600 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013601 // The max adjustment doesn't allow this app to be anything
13602 // below foreground, so it is not worth doing work for it.
13603 app.adjType = "fixed";
13604 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013605 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013606 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013607 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013608 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013609 // System process can do UI, and when they do we want to have
13610 // them trim their memory after the user leaves the UI. To
13611 // facilitate this, here we need to determine whether or not it
13612 // is currently showing UI.
13613 app.systemNoUi = true;
13614 if (app == TOP_APP) {
13615 app.systemNoUi = false;
13616 } else if (activitiesSize > 0) {
13617 for (int j = 0; j < activitiesSize; j++) {
13618 final ActivityRecord r = app.activities.get(j);
13619 if (r.visible) {
13620 app.systemNoUi = false;
13621 break;
13622 }
13623 }
13624 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013625 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013626 }
13627
13628 final boolean hadForegroundActivities = app.foregroundActivities;
13629
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013630 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013631 app.keeping = false;
13632 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013633
The Android Open Source Project4df24232009-03-05 14:34:35 -080013634 // Determine the importance of the process, starting with most
13635 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013637 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013638 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013639 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013640 // The last app on the list is the foreground app.
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 = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013644 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013645 } else if (app.instrumentationClass != null) {
13646 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013647 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013648 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013649 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013650 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013651 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013652 // counts as being in the foreground for OOM killer purposes.
13653 // It's placed in a sched group based on the nature of the
13654 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013655 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013656 schedGroup = (queue == mFgBroadcastQueue)
13657 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013658 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013659 } else if (app.executingServices.size() > 0) {
13660 // An app that is currently executing a service callback also
13661 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013662 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013663 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013664 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013665 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013666 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013667 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013668 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013669 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013670 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013671 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013672 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013673 // A very not-needed process. If this is lower in the lru list,
13674 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013675 adj = hiddenAdj;
13676 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013677 app.hidden = true;
13678 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013679 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013680 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013681
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013682 boolean hasStoppingActivities = false;
13683
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013684 // Examine all activities if not already foreground.
13685 if (!app.foregroundActivities && activitiesSize > 0) {
13686 for (int j = 0; j < activitiesSize; j++) {
13687 final ActivityRecord r = app.activities.get(j);
13688 if (r.visible) {
13689 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013690 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13691 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013692 app.adjType = "visible";
13693 }
13694 schedGroup = Process.THREAD_GROUP_DEFAULT;
13695 app.hidden = false;
13696 app.foregroundActivities = true;
13697 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013698 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013699 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13700 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013701 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013702 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013703 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013704 app.foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013705 } else if (r.state == ActivityState.STOPPING) {
13706 // We will apply the actual adjustment later, because
13707 // we want to allow this process to immediately go through
13708 // any memory trimming that is in effect.
13709 app.hidden = false;
13710 app.foregroundActivities = true;
13711 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013712 }
13713 }
13714 }
13715
Dianne Hackborn7d608422011-08-07 16:24:18 -070013716 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013717 if (app.foregroundServices) {
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 = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013722 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013723 } else if (app.forcingToForeground != null) {
13724 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013725 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013726 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013727 app.adjType = "force-foreground";
13728 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013729 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013730 }
13731 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013732
Dianne Hackborn7d608422011-08-07 16:24:18 -070013733 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013734 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013735 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013736 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013737 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013738 app.adjType = "heavy";
13739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013740
Dianne Hackborn7d608422011-08-07 16:24:18 -070013741 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013742 // This process is hosting what we currently consider to be the
13743 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013744 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013745 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013746 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013747 app.adjType = "home";
13748 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013749
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013750 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13751 && app.activities.size() > 0) {
13752 // This was the previous process that showed UI to the user.
13753 // We want to try to keep it around more aggressively, to give
13754 // a good experience around switching between two apps.
13755 adj = ProcessList.PREVIOUS_APP_ADJ;
13756 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13757 app.hidden = false;
13758 app.adjType = "previous";
13759 }
13760
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013761 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13762 + " reason=" + app.adjType);
13763
The Android Open Source Project4df24232009-03-05 14:34:35 -080013764 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013765 // there are applications dependent on our services or providers, but
13766 // this gives us a baseline and makes sure we don't get into an
13767 // infinite recursion.
13768 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013769 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013770
Christopher Tate6fa95972009-06-05 18:43:55 -070013771 if (mBackupTarget != null && app == mBackupTarget.app) {
13772 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013773 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013774 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013775 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013776 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013777 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013778 }
13779 }
13780
Dianne Hackborn7d608422011-08-07 16:24:18 -070013781 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013782 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 final long now = SystemClock.uptimeMillis();
13784 // This process is more important if the top activity is
13785 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013786 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013787 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013788 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013789 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013790 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013791 // If this process has shown some UI, let it immediately
13792 // go to the LRU list because it may be pretty heavy with
13793 // UI stuff. We'll tag it with a label just to help
13794 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013795 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013796 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013797 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013798 } else {
13799 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13800 // This service has seen some activity within
13801 // recent memory, so we will keep its process ahead
13802 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013803 if (adj > ProcessList.SERVICE_ADJ) {
13804 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013805 app.adjType = "started-services";
13806 app.hidden = false;
13807 }
13808 }
13809 // If we have let the service slide into the background
13810 // state, still have some text describing what it is doing
13811 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013812 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013813 app.adjType = "started-bg-services";
13814 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013815 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013816 // Don't kill this process because it is doing work; it
13817 // has said it is doing work.
13818 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013819 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013820 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013821 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013822 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013823 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013824 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013825 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013826 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013827 // XXX should compute this based on the max of
13828 // all connected clients.
13829 ConnectionRecord cr = clist.get(i);
13830 if (cr.binding.client == app) {
13831 // Binding to ourself is not interesting.
13832 continue;
13833 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013834 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013835 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013836 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013837 int myHiddenAdj = hiddenAdj;
13838 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013839 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013840 myHiddenAdj = client.hiddenAdj;
13841 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013842 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013843 }
13844 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013845 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013846 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013847 String adjType = null;
13848 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13849 // Not doing bind OOM management, so treat
13850 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013851 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013852 // If this process has shown some UI, let it immediately
13853 // go to the LRU list because it may be pretty heavy with
13854 // UI stuff. We'll tag it with a label just to help
13855 // debug and understand what is going on.
13856 if (adj > clientAdj) {
13857 adjType = "bound-bg-ui-services";
13858 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013859 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013860 clientAdj = adj;
13861 } else {
13862 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13863 // This service has not seen activity within
13864 // recent memory, so allow it to drop to the
13865 // LRU list if there is no other reason to keep
13866 // it around. We'll also tag it with a label just
13867 // to help debug and undertand what is going on.
13868 if (adj > clientAdj) {
13869 adjType = "bound-bg-services";
13870 }
13871 clientAdj = adj;
13872 }
13873 }
13874 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013875 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013876 // If this process has recently shown UI, and
13877 // the process that is binding to it is less
13878 // important than being visible, then we don't
13879 // care about the binding as much as we care
13880 // about letting this process get into the LRU
13881 // list to be killed and restarted if needed for
13882 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013883 if (app.hasShownUi && app != mHomeProcess
13884 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013885 adjType = "bound-bg-ui-services";
13886 } else {
13887 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13888 |Context.BIND_IMPORTANT)) != 0) {
13889 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013890 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13891 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13892 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13893 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13894 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013895 adj = clientAdj;
13896 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013897 app.pendingUiClean = true;
13898 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13899 adj = ProcessList.VISIBLE_APP_ADJ;
13900 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013901 }
13902 if (!client.hidden) {
13903 app.hidden = false;
13904 }
13905 if (client.keeping) {
13906 app.keeping = true;
13907 }
13908 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013909 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013910 }
13911 if (adjType != null) {
13912 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013913 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13914 .REASON_SERVICE_IN_USE;
13915 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013916 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013917 app.adjTarget = s.name;
13918 }
13919 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13920 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13921 schedGroup = Process.THREAD_GROUP_DEFAULT;
13922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013923 }
13924 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013925 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13926 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013927 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013928 (a.visible || a.state == ActivityState.RESUMED
13929 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013930 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013931 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13932 schedGroup = Process.THREAD_GROUP_DEFAULT;
13933 }
13934 app.hidden = false;
13935 app.adjType = "service";
13936 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13937 .REASON_SERVICE_IN_USE;
13938 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013939 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013940 app.adjTarget = s.name;
13941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013943 }
13944 }
13945 }
13946 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013947
Dianne Hackborn287952c2010-09-22 22:34:31 -070013948 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013949 // would like to avoid killing it unless it would prevent the current
13950 // application from running. By default we put the process in
13951 // with the rest of the background processes; as we scan through
13952 // its services we may bump it up from there.
13953 if (adj > hiddenAdj) {
13954 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013955 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013956 app.adjType = "bg-services";
13957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013958 }
13959
Dianne Hackborn7d608422011-08-07 16:24:18 -070013960 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013961 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013962 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013963 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013964 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013965 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013966 if (cpr.clients.size() != 0) {
13967 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013968 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013970 if (client == app) {
13971 // Being our own client is not interesting.
13972 continue;
13973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013974 int myHiddenAdj = hiddenAdj;
13975 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013976 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013977 myHiddenAdj = client.hiddenAdj;
13978 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013979 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013980 }
13981 }
13982 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013983 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013984 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013985 if (app.hasShownUi && app != mHomeProcess
13986 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013987 app.adjType = "bg-ui-provider";
13988 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013989 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13990 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013991 app.adjType = "provider";
13992 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013993 if (!client.hidden) {
13994 app.hidden = false;
13995 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013996 if (client.keeping) {
13997 app.keeping = true;
13998 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013999 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14000 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014001 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014002 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014003 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014004 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014005 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14006 schedGroup = Process.THREAD_GROUP_DEFAULT;
14007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014008 }
14009 }
14010 // If the provider has external (non-framework) process
14011 // dependencies, ensure that its adjustment is at least
14012 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080014013 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014014 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14015 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014016 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014017 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014018 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014019 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014020 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014021 }
14022 }
14023 }
14024 }
14025
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014026 if (adj == ProcessList.SERVICE_ADJ) {
14027 if (doingAll) {
14028 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14029 mNewNumServiceProcs++;
14030 }
14031 if (app.serviceb) {
14032 adj = ProcessList.SERVICE_B_ADJ;
14033 }
14034 } else {
14035 app.serviceb = false;
14036 }
14037
14038 app.nonStoppingAdj = adj;
14039
14040 if (hasStoppingActivities) {
14041 // Only upgrade adjustment.
14042 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14043 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14044 app.adjType = "stopping";
14045 }
14046 }
14047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014048 app.curRawAdj = adj;
14049
Joe Onorato8a9b2202010-02-26 18:56:32 -080014050 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014051 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14052 if (adj > app.maxAdj) {
14053 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014054 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014055 schedGroup = Process.THREAD_GROUP_DEFAULT;
14056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014057 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014058 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014059 app.keeping = true;
14060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014061
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014062 if (app.hasAboveClient) {
14063 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14064 // then we need to drop its adjustment to be lower than the service's
14065 // in order to honor the request. We want to drop it by one adjustment
14066 // level... but there is special meaning applied to various levels so
14067 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014068 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014069 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014070 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14071 adj = ProcessList.VISIBLE_APP_ADJ;
14072 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14073 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14074 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14075 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014076 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014077 adj++;
14078 }
14079 }
14080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014081 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014082 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014083
14084 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070014085 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
14086 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014087 }
14088
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014089 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014090 }
14091
14092 /**
14093 * Ask a given process to GC right now.
14094 */
14095 final void performAppGcLocked(ProcessRecord app) {
14096 try {
14097 app.lastRequestedGc = SystemClock.uptimeMillis();
14098 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014099 if (app.reportLowMemory) {
14100 app.reportLowMemory = false;
14101 app.thread.scheduleLowMemory();
14102 } else {
14103 app.thread.processInBackground();
14104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 }
14106 } catch (Exception e) {
14107 // whatever.
14108 }
14109 }
14110
14111 /**
14112 * Returns true if things are idle enough to perform GCs.
14113 */
Josh Bartel7f208742010-02-25 11:01:44 -060014114 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014115 boolean processingBroadcasts = false;
14116 for (BroadcastQueue q : mBroadcastQueues) {
14117 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14118 processingBroadcasts = true;
14119 }
14120 }
14121 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014122 && (mSleeping || (mMainStack.mResumedActivity != null &&
14123 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014124 }
14125
14126 /**
14127 * Perform GCs on all processes that are waiting for it, but only
14128 * if things are idle.
14129 */
14130 final void performAppGcsLocked() {
14131 final int N = mProcessesToGc.size();
14132 if (N <= 0) {
14133 return;
14134 }
Josh Bartel7f208742010-02-25 11:01:44 -060014135 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014136 while (mProcessesToGc.size() > 0) {
14137 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014138 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014139 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14140 <= SystemClock.uptimeMillis()) {
14141 // To avoid spamming the system, we will GC processes one
14142 // at a time, waiting a few seconds between each.
14143 performAppGcLocked(proc);
14144 scheduleAppGcsLocked();
14145 return;
14146 } else {
14147 // It hasn't been long enough since we last GCed this
14148 // process... put it in the list to wait for its time.
14149 addProcessToGcListLocked(proc);
14150 break;
14151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014152 }
14153 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014154
14155 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014156 }
14157 }
14158
14159 /**
14160 * If all looks good, perform GCs on all processes waiting for them.
14161 */
14162 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014163 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014164 performAppGcsLocked();
14165 return;
14166 }
14167 // Still not idle, wait some more.
14168 scheduleAppGcsLocked();
14169 }
14170
14171 /**
14172 * Schedule the execution of all pending app GCs.
14173 */
14174 final void scheduleAppGcsLocked() {
14175 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014176
14177 if (mProcessesToGc.size() > 0) {
14178 // Schedule a GC for the time to the next process.
14179 ProcessRecord proc = mProcessesToGc.get(0);
14180 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14181
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014182 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014183 long now = SystemClock.uptimeMillis();
14184 if (when < (now+GC_TIMEOUT)) {
14185 when = now + GC_TIMEOUT;
14186 }
14187 mHandler.sendMessageAtTime(msg, when);
14188 }
14189 }
14190
14191 /**
14192 * Add a process to the array of processes waiting to be GCed. Keeps the
14193 * list in sorted order by the last GC time. The process can't already be
14194 * on the list.
14195 */
14196 final void addProcessToGcListLocked(ProcessRecord proc) {
14197 boolean added = false;
14198 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14199 if (mProcessesToGc.get(i).lastRequestedGc <
14200 proc.lastRequestedGc) {
14201 added = true;
14202 mProcessesToGc.add(i+1, proc);
14203 break;
14204 }
14205 }
14206 if (!added) {
14207 mProcessesToGc.add(0, proc);
14208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014209 }
14210
14211 /**
14212 * Set up to ask a process to GC itself. This will either do it
14213 * immediately, or put it on the list of processes to gc the next
14214 * time things are idle.
14215 */
14216 final void scheduleAppGcLocked(ProcessRecord app) {
14217 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014218 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014219 return;
14220 }
14221 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014222 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014223 scheduleAppGcsLocked();
14224 }
14225 }
14226
Dianne Hackborn287952c2010-09-22 22:34:31 -070014227 final void checkExcessivePowerUsageLocked(boolean doKills) {
14228 updateCpuStatsNow();
14229
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014230 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014231 boolean doWakeKills = doKills;
14232 boolean doCpuKills = doKills;
14233 if (mLastPowerCheckRealtime == 0) {
14234 doWakeKills = false;
14235 }
14236 if (mLastPowerCheckUptime == 0) {
14237 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014238 }
14239 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014240 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014241 }
14242 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014243 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14244 final long curUptime = SystemClock.uptimeMillis();
14245 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14246 mLastPowerCheckRealtime = curRealtime;
14247 mLastPowerCheckUptime = curUptime;
14248 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14249 doWakeKills = false;
14250 }
14251 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14252 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014253 }
14254 int i = mLruProcesses.size();
14255 while (i > 0) {
14256 i--;
14257 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014258 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014259 long wtime;
14260 synchronized (stats) {
14261 wtime = stats.getProcessWakeTime(app.info.uid,
14262 app.pid, curRealtime);
14263 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014264 long wtimeUsed = wtime - app.lastWakeTime;
14265 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14266 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014267 StringBuilder sb = new StringBuilder(128);
14268 sb.append("Wake for ");
14269 app.toShortString(sb);
14270 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014271 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014272 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014273 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014274 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014275 sb.append((wtimeUsed*100)/realtimeSince);
14276 sb.append("%)");
14277 Slog.i(TAG, sb.toString());
14278 sb.setLength(0);
14279 sb.append("CPU for ");
14280 app.toShortString(sb);
14281 sb.append(": over ");
14282 TimeUtils.formatDuration(uptimeSince, sb);
14283 sb.append(" used ");
14284 TimeUtils.formatDuration(cputimeUsed, sb);
14285 sb.append(" (");
14286 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014287 sb.append("%)");
14288 Slog.i(TAG, sb.toString());
14289 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014290 // If a process has held a wake lock for more
14291 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014292 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014293 if (doWakeKills && realtimeSince > 0
14294 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14295 synchronized (stats) {
14296 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14297 realtimeSince, wtimeUsed);
14298 }
14299 Slog.w(TAG, "Excessive wake lock in " + app.processName
14300 + " (pid " + app.pid + "): held " + wtimeUsed
14301 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014302 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14303 app.processName, app.setAdj, "excessive wake lock");
14304 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014305 } else if (doCpuKills && uptimeSince > 0
14306 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14307 synchronized (stats) {
14308 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14309 uptimeSince, cputimeUsed);
14310 }
14311 Slog.w(TAG, "Excessive CPU in " + app.processName
14312 + " (pid " + app.pid + "): used " + cputimeUsed
14313 + " during " + uptimeSince);
14314 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14315 app.processName, app.setAdj, "excessive cpu");
14316 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014317 } else {
14318 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014319 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014320 }
14321 }
14322 }
14323 }
14324
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014325 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014326 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014327 app.hiddenAdj = hiddenAdj;
14328
14329 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014330 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014331 }
14332
Dianne Hackborn287952c2010-09-22 22:34:31 -070014333 final boolean wasKeeping = app.keeping;
14334
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014335 boolean success = true;
14336
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014337 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014338
Jeff Brown10e89712011-07-08 18:52:57 -070014339 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014340 if (wasKeeping && !app.keeping) {
14341 // This app is no longer something we want to keep. Note
14342 // its current wake lock time to later know to kill it if
14343 // it is not behaving well.
14344 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14345 synchronized (stats) {
14346 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14347 app.pid, SystemClock.elapsedRealtime());
14348 }
14349 app.lastCpuTime = app.curCpuTime;
14350 }
14351
14352 app.setRawAdj = app.curRawAdj;
14353 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014354
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014355 if (app.curAdj != app.setAdj) {
14356 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014357 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014358 TAG, "Set " + app.pid + " " + app.processName +
14359 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014360 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014361 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014362 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014363 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014364 }
14365 }
14366 if (app.setSchedGroup != app.curSchedGroup) {
14367 app.setSchedGroup = app.curSchedGroup;
14368 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14369 "Setting process group of " + app.processName
14370 + " to " + app.curSchedGroup);
14371 if (app.waitingToKill != null &&
14372 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14373 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14374 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14375 app.processName, app.setAdj, app.waitingToKill);
14376 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014377 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014378 } else {
14379 if (true) {
14380 long oldId = Binder.clearCallingIdentity();
14381 try {
14382 Process.setProcessGroup(app.pid, app.curSchedGroup);
14383 } catch (Exception e) {
14384 Slog.w(TAG, "Failed setting process group of " + app.pid
14385 + " to " + app.curSchedGroup);
14386 e.printStackTrace();
14387 } finally {
14388 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014389 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014390 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014391 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014392 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014393 app.thread.setSchedulingGroup(app.curSchedGroup);
14394 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014395 }
14396 }
14397 }
14398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014399 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014400 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014401 }
14402
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014403 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014404 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014405 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014406 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014407 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014408 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014409 }
14410 }
14411 return resumedActivity;
14412 }
14413
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014414 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014415 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014416 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14417 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014418 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14419 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014420
14421 mAdjSeq++;
14422
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014423 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014424 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14425 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014426 if (nowHidden != wasHidden) {
14427 // Changed to/from hidden state, so apps after it in the LRU
14428 // list may also be changed.
14429 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014430 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014431 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014432 }
14433
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014434 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014435 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014436 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14437
14438 if (false) {
14439 RuntimeException e = new RuntimeException();
14440 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014441 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014442 }
14443
14444 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014445 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014446
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014447 // Let's determine how many processes we have running vs.
14448 // how many slots we have for background processes; we may want
14449 // to put multiple processes in a slot of there are enough of
14450 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014451 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014452 int factor = (mLruProcesses.size()-4)/numSlots;
14453 if (factor < 1) factor = 1;
14454 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014455 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014456 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014457
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014458 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014459 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014460 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014461 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014462 while (i > 0) {
14463 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014464 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014465 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014466 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14467 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014468 && app.curAdj == curHiddenAdj) {
14469 step++;
14470 if (step >= factor) {
14471 step = 0;
14472 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014473 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014474 }
14475 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014476 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014477 numHidden++;
14478 if (numHidden > mProcessLimit) {
14479 Slog.i(TAG, "No longer want " + app.processName
14480 + " (pid " + app.pid + "): hidden #" + numHidden);
14481 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14482 app.processName, app.setAdj, "too many background");
14483 app.killedBackground = true;
14484 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014485 }
14486 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014487 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14488 // If this is an isolated process, and there are no
14489 // services running in it, then the process is no longer
14490 // needed. We agressively kill these because we can by
14491 // definition not re-use the same process again, and it is
14492 // good to avoid having whatever code was running in them
14493 // left sitting around after no longer needed.
14494 Slog.i(TAG, "Isolated process " + app.processName
14495 + " (pid " + app.pid + ") no longer needed");
14496 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14497 app.processName, app.setAdj, "isolated not needed");
14498 app.killedBackground = true;
14499 Process.killProcessQuiet(app.pid);
14500 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014501 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14502 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14503 && !app.killedBackground) {
14504 numTrimming++;
14505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014506 }
14507 }
14508
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014509 mNumServiceProcs = mNewNumServiceProcs;
14510
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014511 // Now determine the memory trimming level of background processes.
14512 // Unfortunately we need to start at the back of the list to do this
14513 // properly. We only do this if the number of background apps we
14514 // are managing to keep around is less than half the maximum we desire;
14515 // if we are keeping a good number around, we'll let them use whatever
14516 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014517 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014518 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014519 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014520 int minFactor = 2;
14521 if (mHomeProcess != null) minFactor++;
14522 if (mPreviousProcess != null) minFactor++;
14523 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014524 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014525 int fgTrimLevel;
14526 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14527 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14528 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14529 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14530 } else {
14531 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14532 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014533 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014534 for (i=0; i<N; i++) {
14535 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014536 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14537 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014538 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014539 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14540 try {
14541 app.thread.scheduleTrimMemory(curLevel);
14542 } catch (RemoteException e) {
14543 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014544 if (false) {
14545 // For now we won't do this; our memory trimming seems
14546 // to be good enough at this point that destroying
14547 // activities causes more harm than good.
14548 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14549 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014550 // Need to do this on its own message because the stack may not
14551 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014552 // For these apps we will also finish their activities
14553 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014554 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014555 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014556 }
14557 }
14558 app.trimMemoryLevel = curLevel;
14559 step++;
14560 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014561 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014562 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014563 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14564 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014565 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014566 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14567 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014568 break;
14569 }
14570 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014571 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014572 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014573 && app.thread != null) {
14574 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014575 app.thread.scheduleTrimMemory(
14576 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014577 } catch (RemoteException e) {
14578 }
14579 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014580 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014581 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014582 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014583 && app.pendingUiClean) {
14584 // If this application is now in the background and it
14585 // had done UI, then give it the special trim level to
14586 // have it free UI resources.
14587 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14588 if (app.trimMemoryLevel < level && app.thread != null) {
14589 try {
14590 app.thread.scheduleTrimMemory(level);
14591 } catch (RemoteException e) {
14592 }
14593 }
14594 app.pendingUiClean = false;
14595 }
14596 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014597 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014598 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014599 } catch (RemoteException e) {
14600 }
14601 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014602 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014603 }
14604 }
14605 } else {
14606 final int N = mLruProcesses.size();
14607 for (i=0; i<N; i++) {
14608 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014609 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014610 && app.pendingUiClean) {
14611 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14612 && app.thread != null) {
14613 try {
14614 app.thread.scheduleTrimMemory(
14615 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14616 } catch (RemoteException e) {
14617 }
14618 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014619 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014620 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014621 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014622 }
14623 }
14624
14625 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014626 // Need to do this on its own message because the stack may not
14627 // be in a consistent state at this point.
14628 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014630 }
14631
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014632 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014633 synchronized (this) {
14634 int i;
14635
14636 // First remove any unused application processes whose package
14637 // has been removed.
14638 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14639 final ProcessRecord app = mRemovedProcesses.get(i);
14640 if (app.activities.size() == 0
14641 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014642 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014643 TAG, "Exiting empty application process "
14644 + app.processName + " ("
14645 + (app.thread != null ? app.thread.asBinder() : null)
14646 + ")\n");
14647 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014648 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14649 app.processName, app.setAdj, "empty");
14650 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014651 } else {
14652 try {
14653 app.thread.scheduleExit();
14654 } catch (Exception e) {
14655 // Ignore exceptions.
14656 }
14657 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014658 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014659 mRemovedProcesses.remove(i);
14660
14661 if (app.persistent) {
14662 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014663 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014664 }
14665 }
14666 }
14667 }
14668
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014669 // Now update the oom adj for all processes.
14670 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014671 }
14672 }
14673
14674 /** This method sends the specified signal to each of the persistent apps */
14675 public void signalPersistentProcesses(int sig) throws RemoteException {
14676 if (sig != Process.SIGNAL_USR1) {
14677 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14678 }
14679
14680 synchronized (this) {
14681 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14682 != PackageManager.PERMISSION_GRANTED) {
14683 throw new SecurityException("Requires permission "
14684 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14685 }
14686
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014687 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14688 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014689 if (r.thread != null && r.persistent) {
14690 Process.sendSignal(r.pid, sig);
14691 }
14692 }
14693 }
14694 }
14695
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014696 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14697 if (proc == null || proc == mProfileProc) {
14698 proc = mProfileProc;
14699 path = mProfileFile;
14700 profileType = mProfileType;
14701 clearProfilerLocked();
14702 }
14703 if (proc == null) {
14704 return;
14705 }
14706 try {
14707 proc.thread.profilerControl(false, path, null, profileType);
14708 } catch (RemoteException e) {
14709 throw new IllegalStateException("Process disappeared");
14710 }
14711 }
14712
14713 private void clearProfilerLocked() {
14714 if (mProfileFd != null) {
14715 try {
14716 mProfileFd.close();
14717 } catch (IOException e) {
14718 }
14719 }
14720 mProfileApp = null;
14721 mProfileProc = null;
14722 mProfileFile = null;
14723 mProfileType = 0;
14724 mAutoStopProfiler = false;
14725 }
14726
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014727 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014728 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014729
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014730 try {
14731 synchronized (this) {
14732 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14733 // its own permission.
14734 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14735 != PackageManager.PERMISSION_GRANTED) {
14736 throw new SecurityException("Requires permission "
14737 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014738 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014739
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014740 if (start && fd == null) {
14741 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014742 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014743
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014744 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014745 if (process != null) {
14746 try {
14747 int pid = Integer.parseInt(process);
14748 synchronized (mPidsSelfLocked) {
14749 proc = mPidsSelfLocked.get(pid);
14750 }
14751 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014752 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014753
14754 if (proc == null) {
14755 HashMap<String, SparseArray<ProcessRecord>> all
14756 = mProcessNames.getMap();
14757 SparseArray<ProcessRecord> procs = all.get(process);
14758 if (procs != null && procs.size() > 0) {
14759 proc = procs.valueAt(0);
14760 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014761 }
14762 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014763
14764 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014765 throw new IllegalArgumentException("Unknown process: " + process);
14766 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014767
14768 if (start) {
14769 stopProfilerLocked(null, null, 0);
14770 setProfileApp(proc.info, proc.processName, path, fd, false);
14771 mProfileProc = proc;
14772 mProfileType = profileType;
14773 try {
14774 fd = fd.dup();
14775 } catch (IOException e) {
14776 fd = null;
14777 }
14778 proc.thread.profilerControl(start, path, fd, profileType);
14779 fd = null;
14780 mProfileFd = null;
14781 } else {
14782 stopProfilerLocked(proc, path, profileType);
14783 if (fd != null) {
14784 try {
14785 fd.close();
14786 } catch (IOException e) {
14787 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014788 }
14789 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014790
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014791 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014792 }
14793 } catch (RemoteException e) {
14794 throw new IllegalStateException("Process disappeared");
14795 } finally {
14796 if (fd != null) {
14797 try {
14798 fd.close();
14799 } catch (IOException e) {
14800 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014801 }
14802 }
14803 }
Andy McFadden824c5102010-07-09 16:26:57 -070014804
14805 public boolean dumpHeap(String process, boolean managed,
14806 String path, ParcelFileDescriptor fd) throws RemoteException {
14807
14808 try {
14809 synchronized (this) {
14810 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14811 // its own permission (same as profileControl).
14812 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14813 != PackageManager.PERMISSION_GRANTED) {
14814 throw new SecurityException("Requires permission "
14815 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14816 }
14817
14818 if (fd == null) {
14819 throw new IllegalArgumentException("null fd");
14820 }
14821
14822 ProcessRecord proc = null;
14823 try {
14824 int pid = Integer.parseInt(process);
14825 synchronized (mPidsSelfLocked) {
14826 proc = mPidsSelfLocked.get(pid);
14827 }
14828 } catch (NumberFormatException e) {
14829 }
14830
14831 if (proc == null) {
14832 HashMap<String, SparseArray<ProcessRecord>> all
14833 = mProcessNames.getMap();
14834 SparseArray<ProcessRecord> procs = all.get(process);
14835 if (procs != null && procs.size() > 0) {
14836 proc = procs.valueAt(0);
14837 }
14838 }
14839
14840 if (proc == null || proc.thread == null) {
14841 throw new IllegalArgumentException("Unknown process: " + process);
14842 }
14843
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014844 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14845 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014846 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14847 throw new SecurityException("Process not debuggable: " + proc);
14848 }
14849 }
14850
14851 proc.thread.dumpHeap(managed, path, fd);
14852 fd = null;
14853 return true;
14854 }
14855 } catch (RemoteException e) {
14856 throw new IllegalStateException("Process disappeared");
14857 } finally {
14858 if (fd != null) {
14859 try {
14860 fd.close();
14861 } catch (IOException e) {
14862 }
14863 }
14864 }
14865 }
14866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014867 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14868 public void monitor() {
14869 synchronized (this) { }
14870 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014871
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014872 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014873 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14874 ProcessRecord processRecord = mLruProcesses.get(i);
14875 try {
14876 if (processRecord.thread != null) {
14877 processRecord.thread.setCoreSettings(settings);
14878 }
14879 } catch (RemoteException re) {
14880 /* ignore */
14881 }
14882 }
14883 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014884
14885 // Multi-user methods
14886
Amith Yamasani742a6712011-05-04 14:49:28 -070014887 private int mCurrentUserId;
14888 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14889
14890 public boolean switchUser(int userId) {
14891 final int callingUid = Binder.getCallingUid();
14892 if (callingUid != 0 && callingUid != Process.myUid()) {
14893 Slog.e(TAG, "Trying to switch user from unauthorized app");
14894 return false;
14895 }
14896 if (mCurrentUserId == userId)
14897 return true;
14898
14899 synchronized (this) {
14900 // Check if user is already logged in, otherwise check if user exists first before
14901 // adding to the list of logged in users.
14902 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14903 if (!userExists(userId)) {
14904 return false;
14905 }
14906 mLoggedInUsers.append(userId, userId);
14907 }
14908
14909 mCurrentUserId = userId;
14910 boolean haveActivities = mMainStack.switchUser(userId);
14911 if (!haveActivities) {
14912 startHomeActivityLocked(userId);
14913 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014914
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014915 }
Amith Yamasani13593602012-03-22 16:16:17 -070014916
14917 // Inform of user switch
14918 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14919 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14920 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14921
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014922 return true;
14923 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014924
Amith Yamasani52f1d752012-03-28 18:19:29 -070014925 @Override
14926 public UserInfo getCurrentUser() throws RemoteException {
14927 final int callingUid = Binder.getCallingUid();
14928 if (callingUid != 0 && callingUid != Process.myUid()) {
14929 Slog.e(TAG, "Trying to get user from unauthorized app");
14930 return null;
14931 }
14932 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14933 }
14934
Amith Yamasani13593602012-03-22 16:16:17 -070014935 private void onUserRemoved(Intent intent) {
14936 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14937 if (extraUserId < 1) return;
14938
14939 // Kill all the processes for the user
14940 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14941 synchronized (this) {
14942 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14943 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14944 SparseArray<ProcessRecord> uids = uidMap.getValue();
14945 for (int i = 0; i < uids.size(); i++) {
14946 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14947 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14948 }
14949 }
14950 }
14951
14952 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14953 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14954 false, false, true, true, extraUserId);
14955 }
14956 }
14957 }
14958
Amith Yamasani742a6712011-05-04 14:49:28 -070014959 private boolean userExists(int userId) {
14960 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014961 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14962 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014963 } catch (RemoteException re) {
14964 // Won't happen, in same process
14965 }
14966
14967 return false;
14968 }
14969
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014970 private void checkValidCaller(int uid, int userId) {
14971 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14972
14973 throw new SecurityException("Caller uid=" + uid
14974 + " is not privileged to communicate with user=" + userId);
14975 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014976
14977 private int applyUserId(int uid, int userId) {
14978 return UserId.getUid(userId, uid);
14979 }
14980
14981 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014982 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014983 ApplicationInfo newInfo = new ApplicationInfo(info);
14984 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014985 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14986 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014987 return newInfo;
14988 }
14989
14990 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014991 if (aInfo == null
14992 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014993 return aInfo;
14994 }
14995
14996 ActivityInfo info = new ActivityInfo(aInfo);
14997 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14998 return info;
14999 }
15000
15001 static class ServiceMap {
15002
15003 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15004 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15005 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15006 mServicesByIntentPerUser = new SparseArray<
15007 HashMap<Intent.FilterComparison, ServiceRecord>>();
15008
15009 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15010 // TODO: Deal with global services
15011 if (DEBUG_MU)
15012 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15013 return getServices(callingUser).get(name);
15014 }
15015
15016 ServiceRecord getServiceByName(ComponentName name) {
15017 return getServiceByName(name, -1);
15018 }
15019
15020 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15021 // TODO: Deal with global services
15022 if (DEBUG_MU)
15023 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15024 return getServicesByIntent(callingUser).get(filter);
15025 }
15026
15027 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15028 return getServiceByIntent(filter, -1);
15029 }
15030
15031 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15032 // TODO: Deal with global services
15033 getServices(callingUser).put(name, value);
15034 }
15035
15036 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15037 ServiceRecord value) {
15038 // TODO: Deal with global services
15039 getServicesByIntent(callingUser).put(filter, value);
15040 }
15041
15042 void removeServiceByName(ComponentName name, int callingUser) {
15043 // TODO: Deal with global services
15044 ServiceRecord removed = getServices(callingUser).remove(name);
15045 if (DEBUG_MU)
15046 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15047 + " removed=" + removed);
15048 }
15049
15050 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15051 // TODO: Deal with global services
15052 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15053 if (DEBUG_MU)
15054 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15055 + " removed=" + removed);
15056 }
15057
15058 Collection<ServiceRecord> getAllServices(int callingUser) {
15059 // TODO: Deal with global services
15060 return getServices(callingUser).values();
15061 }
15062
15063 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15064 HashMap map = mServicesByNamePerUser.get(callingUser);
15065 if (map == null) {
15066 map = new HashMap<ComponentName, ServiceRecord>();
15067 mServicesByNamePerUser.put(callingUser, map);
15068 }
15069 return map;
15070 }
15071
15072 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15073 int callingUser) {
15074 HashMap map = mServicesByIntentPerUser.get(callingUser);
15075 if (map == null) {
15076 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15077 mServicesByIntentPerUser.put(callingUser, map);
15078 }
15079 return map;
15080 }
15081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015082}